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

eliminating the __typename field from the urql query response prior to performing a mutation

When retrieving data from a GraphQL Server using urql, an additional _typename field is automatically included by urql to track the cache: { __typename "Book" name "test" description "the book" id "hPl3 ...

Customizing page layout for pages wrapped with higher-order components in TypeScript

Looking to add a layout to my page similar to the one in this link: layouts#per-page-layouts The difference is that my page is wrapped with a HOC, so I tried applying getLayout to the higher order component itself like this: PageWithAuth.getLayout Howev ...

Encountering an error message stating "Property '@global' cannot be read from undefined - Issue with NPM linking MUI components"

I have developed a series of React components that wrap Material-UI components and have been bundled into an NPM module. The module functions correctly when installed using the remote package: npm install *name-of-package*, or through local installation: ...

Vuetify vueJS dialog with elevated design

Is there a way to completely remove the elevation of a v-dialog so that it has no shadow at all? The elevation property in the v-dialog itself and using the class as Class = "elevation-0" have not worked for me. Here is the link to the component ...

Populate object values dynamically through function invocations

Currently, I am involved in a project with a VueJS application that incorporates the following helper class and method: class BiometricMap { static get(bioType) { if (!bioType) { return BiometricMap.default(); } const bioTypes = { ...

Is there a way to automatically convert English numbers to Persian/Arabic as soon as a user types them into the input tag?

Currently, I am working with Vuejs and trying to hide the user's characters in an input tag and replace them with my own characters (specifically numbers). I have attempted using @onchange, Watch, as well as getters and setters within computed proper ...

Description: TypeScript type that derives from the third constructor parameter of a generic function

How can I determine the type of constructor props for a generic type? Take a look at this example. type PatchableProps<T> = T extends { [k: string | number]: any } ? { [Key in keyof T]: PatchableProps<T[Key]> } : T | Patch export class ...

The static method in TypeScript is unable to locate the name "interface"

Is it possible to use an interface from a static method? I'm encountering an issue and could really use some help. I've been experimenting with TypeScript, testing out an interface: interface HelloWorldTS { name : string; } Here&ap ...

Steer clear from using the implicit 'any' type while utilizing Object.keys in Typescript

I have a unique situation where I need to loop over an Object while maintaining their type without encountering the error "Element implicitly has an 'any' type because 'ContactList' has no index signature". Despite extensive discussion ...

Unspecified properties emerge post-Angular update

We recently consolidated multiple Angular 16 projects into one NX mono repository using Angular 17. Everything is functioning properly, EXCEPT we have noticed a peculiar change in behavior with our models. Previously, unset properties were simply not displ ...

Angular seed appears to experience a hiccup when the "Loading..." screen persists after the incorporation of a router-outlet

When working on a new Angular seed application using ng new, I encountered an issue where the application would get stuck at "Loading..." after adding the following to app.component.html: <router-outlet></router-outlet> In an attempt to resol ...

What could be causing the error in Angular 2 when using multiple conditions with ng-if?

My aim is to validate if the length of events is 0 and the length of the term is greater than 2 using the code below: <li class="more-result" *ngIf="events?.length == 0 && term.value.length > 2"> <span class="tab-content- ...

Angular 7: Polyfill required for npm package to support 'Class'

I am encountering an issue where my Angular 7-based app is not functioning in Internet Explorer 11. The npm package I am using begins in index.js: class PackageClass { // code } While the app works as intended in other browsers, it fails to open in ...

Adding Typescript to a Nativescript-Vue project: A step-by-step guide

Struggling over the past couple of days to configure Typescript in a basic template-generated Nativescript-Vue project has been quite the challenge. Here's my journey: Initiated the project using this command: ERROR in Entry module not found: Erro ...

Creating a factory class in Typescript that incorporates advanced logic

I have come across an issue with my TypeScript class that inherits another one. I am trying to create a factory class that can generate objects of either type based on simple logic, but it seems to be malfunctioning. Here is the basic Customer class: cla ...

Having trouble getting the Vue.js framework to function properly on a basic HTML page with a CDN implementation

I recently delved into learning vue.js and decided to focus on forms. However, when I tried to open the file using a live server or XAMPP, it didn't work as expected. It had worked fine before, but now I seem to be encountering some issues. Could anyo ...

The mysterious unknown variable dynamically imported: ../views/Admin/Home.vue in Vue3-vue-router4 has sparked curiosity

When utilizing Vue3, Vuerouter4, and Vite I am attempting to import components and routes into the vue router, but I am encountering an error (only for the route that contains children in my paths): This is my router code: import { createRouter, crea ...

Unable to add new tags in Vue multiselect component

Currently, I am utilizing a Vue Multiselect instance with two functions. One function interacts with the database to provide autocomplete functionality, which is working successfully. The second function allows for adding new tags that are not present in t ...

What is the most effective method for transmitting data within your Vue3 application?

What is the best way to pass data between Vue components? I am looking for a method that allows me to fetch data from the backend once and share it across my project seamlessly, but I can't seem to find the right approach. sessionStorage: It works we ...

Updating the Vuex variable's state directly within the template

If we were to take a look at a Vuex setup like this: import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { dialog: false }, mutations: { openTermsAndConditions (state) { ...