Using decorators with NextJS and TypeScript

1.9k views Asked by At

I'm trying to add dependency injection to my NextJS solution using TypeDI.

In tsconfig.js I have the following set

"experimentalDecorators": true,
"emitDecoratorMetadata": true

But when I compile I get the following error:

Error: error: Unexpected token @. Expected this, import, async, function, [ for array literal, { for object literal, @ for decorator, function, class, null, true, false, number, bigint, string, regexp, ` for template literal, (, or an identifier | 8 | @Service() | ^

The only solution I've found for this is to add the following to a babel config file along with the plugins and babel itself.

// .babelrc
{
  "presets": ["next/babel"],
  "plugins": [
    "babel-plugin-transform-typescript-metadata",
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }]
  ]
}

This looks like it might actually make the decorators work, however NextJS 12 has replaced Babel with SWC and also results in a ton of compiler messages which don't look good.

Any ideas?

0

There are 0 answers