Struggling to configure typescript and babel to work together smoothly within webpack

Currently, I am in the process of converting a project to TypeScript, and it is required to utilize decorators on both classes and function parameters:

function(@inject(TYPES.thing) thingy){...}

I believe I am very close to completing this task, just missing one final piece of the puzzle :)

Below is my webpack configuration:

return {
    entry: path.resolve(__dirname, './src/js/Index.ts'),
    output: {
        filename: 'formr.bundle.js',
        path: path.resolve(__dirname, `dist/${argv.mode === 'production' ? 'prod' : 'dev'}/js/`),
        library: 'Formr',
        libraryTarget: "umd"
    },
    devtool: devtool,
    resolve: {
        extensions: [".js", ".ts", ".tsx"]
    },
    mode: argv.mode,
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'babel-loader',
                exclude: '/node_modules/',

                query: {
                    presets: [
                        "@babel/typescript",
                        ['@babel/preset-env', {targets: {browsers: "last 2 versions"}}],
                    ],
                    plugins: [
                        'lodash',
                        ["@babel/plugin-proposal-decorators", {"legacy": true}],
                        "babel-plugin-parameter-decorator",
                        '@babel/plugin-proposal-class-properties',
                        '@babel/plugin-proposal-private-methods',
                        '@babel/plugin-proposal-optional-chaining'
                    ]
                }
            },
            {
                test: /\.js$/,
                use: ["source-map-loader"],
                enforce: "pre"
            },
            {
                test: /\.svg$/,
                loader: 'svg-sprite-loader'
            }
        ],

    },
    plugins: [
        new SpriteLoaderPlugin(),
        new LodashModuleReplacementPlugin()
    ]
}

as well as my tsconfig:

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "Node",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "target": "es5",
    "lib": ["es6", "dom", "es2017.object"],
    "types": ["reflect-metadata"],
    "sourceMap": true,
    "allowJs": true,
    "allowSyntheticDefaultImports": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "./src/**/*"
  ]
}

The specific error encountered during the build process is:

ERROR in ./src/js/plugins/TranslationPlugin.ts
Module build failed (from ./node_modules/babel-loader/lib/index.js):
TypeError: /src/js/plugins/TranslationPlugin.ts: Cannot read property 'referencePaths' of undefined
    at _loop (/node_modules/babel-plugin-parameter-decorator/lib/index.js:117:36)
    ....

This error does not appear if I remove the babel-plugin-parameter-decorator plugin, although doing so results in errors related to lack of support for parameter decorators.

Answer №1

As per information provided in this Stack Overflow response, incorporating babel-plugin-transform-typescript-metadata resolves the issue at hand. Thus, your babel plugins configuration should be updated to include:

...
plugins: [
   'lodash',
   "babel-plugin-transform-typescript-metadata"
   ["@babel/plugin-proposal-decorators", { legacy: true }],
   "babel-plugin-parameter-decorator",
   ["@babel/plugin-proposal-class-properties", { loose: true }],
   'babel/plugin-proposal-private-methods',
   'babel/plugin-proposal-optional-chaining'
]
...

Please confirm if this solution works for you, or share if you have already resolved it as I am also facing similar challenges! (I too find it challenging to integrate babel+typescript with TypeORM)

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

What is the best way to adjust the padding within a mat-expansion-panel-body?

I recently created an expansion panel that is working well, but I am having trouble removing a padding from the subpanel section. Despite my efforts, I haven't been able to find a suitable solution. Here's a link to the panel image: https://i.ss ...

Connect multiple observables together into a single subscription

Within my model class 'Item', I needed to load two separate images from the backend - a sprite-texture and a shadow-texture. To achieve this, I implemented parallel loading and joining of the textures in my Item so that they could be easily acces ...

How can you prevent specific dates from being selected in an Angular Datepicker?

Is there a way to exclude Monday from the "mat-datepicker" component? I've tried implementing the following code in my class component: dateFilter = (_date: any) =>{ let day = _date.getDay(); console.log(day); return day != 1; ...

An error in typescript involving a "const" assertion and a string array

Currently, I am diving into the world of Typescript along with React. However, an error has emerged in my path that I can't seem to figure out. It's puzzling why this issue is occurring in the first place. Allow me to elaborate below. const color ...

Obtain the combination of values within an array object

I am attempting to write the specifications for a function that can take records of any structure and convert the values into a discriminated union. For example: const getKeys = <T extends {key: string}>(items: T[]): T['key'] => { // ...

Sending an array from an Angular component to a .Net Framework ApiController using HttpPost: A quick guide

I am attempting to send an Angular array data to the .Net Framework server side Here is my current code snippet: Angular: see below for code service.ts addRecipient(val:any) { return this.http.post(this.APIUrl+'/recipient',val); ...

how to sort arrays in javascript

When it comes to filtering items based on specific criteria like fruit and vegetable filters, what is the most effective method to retrieve items that meet both filter requirements? fruitfilter: [] = [{fruitname: "apple"} , {fruitname: "orange"}] vegeta ...

Just a straightforward Minimum Working Example, encountering a TypeScript error TS2322 that states the object is not compatible with the type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

Currently, I am immersed in a project involving React and Typescript. I am grappling with error code TS2322 and attempting to resolve it. Error: Type '{ submissionsArray: SubmissionProps[]; }' is not assignable to type 'IntrinsicAttributes ...

What is causing the error message to appear even though the element has been correctly defined? - TypeError: Unable to access the value property of null

Objective: Obtain the value of an HTML element in TypeScript (Angular) Issue: Error: Uncaught (in promise): TypeError: Cannot read property 'value' of null Error Message: TypeError: Cannot read property 'value' of null at UserRegi ...

Utilizing HTML and Ionic 3.x: Implementing a for loop within the HTML file by utilizing "in" instead of "of"

I am working with multiple arrays of objects in my typescript file and I need to simultaneously iterate through them to display their contents in the HTML file. The arrays are always the same size, making it easier to work with. Here is what I currently ha ...

Display notification if the request exceeds the expected duration

Is there a way to display a message when a request is taking too long? For instance, if the request exceeds 10 seconds in duration, I want to show a message asking the user to wait until it finishes. fetchData(url, requestParams) { return this.restServic ...

Why is the type considered a union when comparing any to void?

I was curious to see what would happen when a type was checked if it was void, and I found the result interesting. It seems that when the input is any, a union is returned. Can someone shed some light on why this occurs? type test<T> = T extends void ...

Did Jscript.net already offer many of the same features as TypeScript?

I find myself lacking knowledge about TypeScript. After reading through introductory articles, I fail to see any groundbreaking innovations that justify the widespread praise it has received. [1] In terms of syntax, didn't JScript.net already provide ...

TypeScript encountered an error: The get call is missing 0 type arguments

I encountered a typescript error stating "Expected 0 type arguments, but got 1" in the line where my get call is returning. Can you help me identify what is wrong with my get call in this code snippet? public get(params: SummaryParams): Observable&l ...

Using `babel/register` does not seem to be functioning as expected

I am working on an isomorphic app built in ES6 on the client side using the Babel transpiler. I would like my express server to also utilize the same ES6 syntax as the client code. Unfortunately, attempting to use require('babel/register') has n ...

Analyzing memory consumption by an individual function in a Node.js environment

Our current experiment involves measuring the memory usage of specific functions. Initially, we attempted to utilize process.memoryUsage().heapUsed before and after calling the function, but encountered issues due to the behavior of the garbage collector. ...

Establishing the state using React in conjunction with TypeScript

Struggling to understand how to utilize TypeScript to set the state of my React component. Currently developing a basic Todo list Creating a component for the entire list named: TodoList Desire to populate the list with initial items for testing purpos ...

Strategies for resolving linter problems involving mixins in vue-typescript

Scenario: I am currently working on a project where I am implementing mixins to engage with data from components and other methods. Despite the code functioning as expected, I am encountering errors in Vetur indicating that the method does not exist in ...

Tips for incorporating a svg file into your React project

I am facing an issue with my custom React, Typescript, and Webpack project. I am trying to import a basic .svg file and utilize it in one of my components. However, Typescript is throwing the following error: Cannot find module I have tried installing s ...

When attempting to access http://localhost:3000/traceur in Angular 2 with the angular-in-memory-web-api, a 404 (Not Found) error

Hello, I'm encountering an issue with angular-in-memory-web-api. I have attempted to use angular2-in-memory-web-api in SystemJS and other solutions, but without success. I am currently using the official quickstart template. Thank you for any assistan ...