对于打字稿,当前未启用 'decorators-legacy' 的错误,我设置 experimentalDecorators 和 emitDecoratorMetadata 的事件为 true

for typescript the error for 'decorators-legacy' isn't currently enabled, event I set experimentalDecorators and emitDecoratorMetadata is true

我将 typeorm 与 next.js 和打字稿一起使用,我的 tsconfig.json 是:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext",
      "es5",
      "es6"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "jsx": "preserve"
  },
   include: ...

}

我设置 experimentalDecorator 为真。我的打字稿是 3.9.7,我的 typeorm 是 0.2.25。 编译错误为:

error - ./db/entity/User.ts:7:1
Syntax error: Support for the experimental syntax 'decorators-legacy' isn't currently enabled:

   5 |
   6 |
>  7 | @Entity()
     | ^
   8 | export class User {
   9 |
  10 |     @PrimaryGeneratedColumn()

我已经启用 emitDecoratorMetadata,Hoe 为 tsconfig.json

启用 decorators-legacy

我的一个同事刚刚遇到了同样的问题:这是 Babel 抛出的错误,它无法处理 class 装饰器。 事实上,即使您不在代码中使用 Babel,Next.JS 也会在前端使用。

请确保您没有在前端代码中导入 ./db/entity/User.ts 或任何其他 TypeORM class。

如果您只想导入 User 类型,并使用 TypeScript >= 3.8,您可以使用 type-only imports 来完成此操作。只需在 import 关键字后添加 type。这确保只导入 class 的类型,从而避免整个装饰器问题,因为类型是 ignored/removed by babel.

import type { User } from "path/to/db/entity/User";