typescriptwebpackts-loader

Webpack + ts-loader fails on stage 3 decorators: Unexpected character '@'


The following code:

const decorator = (constructor: any, _context: any) => constructor

@decorator
export class Decorated {}

fails in Webpack + ts-loader with the message: Unexpected character '@'

Relevant part of webpack config:

rules: [
            {
                test: /\.ts$/,
                use: "ts-loader",
                resolve: {
                    extensionAlias: {
                        ".js": [".ts"]
                    }
                }
            }
]

This seems to be a problem in ts-loader, because if experimentalDecorators is enabled it does know what to do with that syntax. It still fails because that flag enables an older decorator proposal. The new (stage 3) proposal is supported since TypeScript 5.

I find it strange that no one seems to have encountered this issue, so I'm assuming that I'm making some silly mistake. Thanks for helping out.


Solution

  • I've been able to reproduce your issue here or on the TS playground.

    In your tsconfig.json, change useDefineForClassFields to false and it should work !