Webpack 4 combines the power of Vue with the versatility of Typescript classes and JavaScript code simultaneously

Currently, I am in the process of migrating JS files to Typescript with the objective of being able to utilize both JS and Typescript classes within Vue. While I understand that I can convert Vue scripts into Typescript, I prefer not to do so at this moment.

The issue arises within a file named component.vue:

this.exceptionHandler = app.resolve('ExceptionHandler');

Upon checking the browser's console, I encounter this error message (the compilation is successful):

"TypeError: Cannot call a class as a function"

The definition of ExceptionHandler exists in a TypeScript file with the extension .ts.

Hence, my question is: Is there a way to first transpile the TS code to JS ES6, then merge the code, and finally use Babel to compile it all to ES5?

Within the TS configuration, I have specified these options:

"lib": ["es7", "es6", "es5", "dom"],
"types": ["reflect-metadata"],
"module": "commonjs",
"target": "es6",

Moreover, in the Webpack 4 configuration:

        {
            test: /\.ts(x?)$/,
            loader: 'babel-loader?presets[]=es2015!ts-loader',
            exclude: [
                "node_modules",
                "vendor",
                "app",
                "public"
            ]
        },

When using just ts-loader, the code functions correctly, however, the compiled JS code version turns out to be ES6 rather than ES5.

Answer №1

For those who are new to Webapack 4, here is a sample webpack configuration file that may come in handy:

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");


let devMode = process.env.NODE_ENV === 'development';

let webUrl = 'http://my-project.localhost/';
if (process.env.NODE_ENV === 'production') {
    webUrl = 'https://my-project.com/';
}
else if (process.env.NODE_ENV === 'development') {
    webUrl = 'http://my-project.localhost/';
}

module.exports = {
    mode: 'development',
    devtool: 'inline-source-map',
    entry: {
        'frontApps': './resources/assets/js/frontApps.ts',
        'backAppsAdmin': './resources/assets/js/backAppsAdmin.ts',
        'styles' : './resources/assets/sass/styles.scss',
        'adminBack' : './resources/assets/sass/admin back/adminBack.scss',
    },
    module: {
        rules: [

            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules|bower_components)/,
                use: [{
                    loader: "babel-loader",
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }]
            },

            {
                test: /\.vue$/,
                loader: 'vue-loader',

                options: {
                    loaders: {
                        js: 'babel-loader',

                        css: ExtractTextPlugin.extract({
                            use: [
                                {
                                    loader: 'css-loader',
                                    options : {
                                        url: false
                                    }
                                }
                            ],
                            fallback: 'vue-style-loader',
                       }),
                    }
                }
            },

            {
                test: /\.ts(x?)$/,
                loader: 'babel-loader?presets[]=@babel/preset-env!ts-loader',
                exclude: [
                    "node_modules",
                    "vendor",
                    "app",
                    "public"
                ]
            },

            {
                test: /\.(sa|sc|c)ss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        options : {
                            url : false,
                            sourceMap: devMode
                        }
                    },
                    {
                        loader: 'sass-loader',
                        options : {
                            processCssUrls : false,
                            sourceMap: devMode
                        }
                    }
                ],
            }
        ]
    },
    output : {
      filename : 'js/[name].js',
      chunkFilename: 'js/[name].js',
      path: path.resolve(__dirname, 'public'),
      publicPath: webUrl,
    },

    optimization: {
        splitChunks: {
            cacheGroups: {
                vendor : {
                    test : '/node_modules/',
                    chunks: 'all',
                    name: 'vendor',
                    priority: 10,
                    enforce: true
                }
            }
        },
    },

    resolve: {
        extensions: [ '.tsx', '.ts', '.js', '.vue' ],
        alias: {
            vue: 'vue/dist/vue.esm.js'
        }
    },

    plugins: [
        new VueLoaderPlugin(),

        new MiniCssExtractPlugin({
            filename: "css/[name]",
            chunkFilename: "css/[id]"
        }),

        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery'
        }),

        new webpack.ProvidePlugin({
            'regeneratorRuntime': 'regenerator-runtime/runtime'
        }),
    ]
};

If you need to integrate SCSS into single file Vue components, follow this syntax:

<style lang="scss" type="text/scss" scoped>

</style>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Warning: Potential Infinite Loop when using Vue JS Category Filter

I developed a program that filters events based on their program and type. The program is working correctly, however, an error message stating "You may have an infinite update loop in a component render function" keeps popping up. I suspect that the issue ...

What is the most effective approach for annotating TypeScript abstract classes that are dynamically loaded?

I am in the process of developing a library that allows for the integration of external implementations, and I am exploring the optimal approach to defining types for these implementations. Illustration abstract class Creature { public abstract makeN ...

The route parameters in Vue SSR are being retrieved from a separate request

I am currently using Akryum/vue-cli-plugin-ssr along with vue-cli, but I have encountered an unusual issue in my Vue SSR application. It seems that the route params are getting mixed up with requests made either before or in parallel to the current one. F ...

Utilizing event bubbling in Angular: a comprehensive guide

When using Jquery, a single event listener was added to the <ul> element in order to listen for events on the current li by utilizing event bubbling. <ul> <li>a</li> <li>b</li> <li>c</li> <li>d< ...

I am attempting to make the fade in and out effect function properly in my slideshow

I've encountered an issue where the fading effect only occurs when the page initially loads and solely on the first image. Subsequently, the fading effect does not work on any other images displayed. This is the CSS code I have implemented by adding ...

Instructions on integrating Realm SDK with Vue3

I've been utilizing Realm SDK in Vue2 with the following syntax: // file scr/plugins/realm.js import Vue from 'vue'; import {App} from 'realm-web; Vue.prototype.realmApp = new App({id: 'artes-realm-vl12'}) //file scr/main.js ...

Change the Vue3 PrimeVue theme or CSS file with a simple click or upon page load

One way to incorporate themes is by importing them in the main.js file at the root of the app: import 'primevue/resources/themes/arya-orange/theme.css'; However, I am exploring ways to dynamically switch CSS files based on the user's system ...

Updating data in Angular reactive forms using asynchronous dropdowns

I am currently developing an Angular application and have encountered an issue that I am unable to resolve by solely reading the documentation. One of the components in my application is responsible for displaying a form: https://i.stack.imgur.com/p5KEU. ...

Acquiring information from a different Vue.js component

I am faced with a puzzle involving 2 components, A and B. Component A: import B from '../components/B.vue'; export default { components: { B }, methods: { test: function() { console.log(B.data().settin ...

What could be causing my TSC to constantly crash whenever I try to utilize MUI props?

Currently in the process of converting a JavaScript project using Next.js and Material UI to TypeScript. This is a snippet of code from one of my components. Whenever I include Props as an intersection type along with MUI's BoxProps, the TypeScript c ...

Mutating properties in VueJs

When I attempted to move a section for filtering from the parent component to a child component, I encountered this error message: "Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a ...

Converting md ElementRef to HtmlElement in Angular 2+: A Step-by-Step Guide

My query is related to retrieving the favorite food input in TypeScript. The input field is defined as: <input mdInput #try placeholder="Favorite food" value="Sushi"> In my TypeScript file, I have accessed this input using: @ViewChild('try ...

How to access enums dynamically using key in TypeScript

export enum MyEnum{ Option1, Option2, Option3 } string selection = 'Option1'; MyEnum[selection] results in an error: The type string cannot be assigned to the type MyEnum On the other hand: MyEnum['Option1'] works as ...

Is it possible to implement lazy loading for data in TypeScript classes?

Looking to optimize my Angular application's data structure when consuming a RESTful API. My goal is to only load necessary data from the server on demand. For instance, if I have a collection of Building objects each with a set of tenant IDs in an a ...

Tips for preventing redundant code in various functions using Vue.js

I am currently in the process of learning both Javascript and Vue.js, and I am facing a challenge with avoiding duplicated code in two functions using Vue.js. Specifically, I am struggling to figure out how to prevent duplication when resetting data with t ...

Exploring nested static properties within TypeScript class structures

Check out this piece of code: class Hey { static a: string static b: string static c: string static setABC(a: string, b: string, c: string) { this.a = a this.b = b this.c = c return this } } class A { static prop1: Hey static ...

Creating dynamic class fields when ngOnInit() is called in Angular

I am trying to dynamically create variables in a class to store values and use them in ngModel and other places. I understand that I can assign values to variables in the ngOnInit() function like this: export class Component implements OnInit{ name: st ...

What is the best way to implement momentJS globally in VueJS 2?

Currently working with Vue.js version 2.6.11 Trying to set up in main.js as follows: import moment from 'moment' moment.locale('nl'); Object.definePrototype(Vue.prototype, '$moment', { value: moment }); Encountering an error ...

Error encountered during secure HTTPS request due to cross-origin request blocking

I am encountering issues with a standard HTTPS Axios request from my Vue-based Frontend to our company's API, which resides on a server with an SSL certificate. testApi() { axios.get('https://rng-hub2.staging.rng:8001/rng/3/') .then ...

The installation of webtorrent-hybrid failed due to the error message "node-pre-gyp: command not found"

I'm currently encountering an issue while attempting to install webtorrent-hybrid for developing an electron p2p application. Vue UI is the framework I am using to handle front-end development, and I have successfully created a new project utilizing v ...