Skip to content

装饰器元数据未发射

快速摘要

你使用依赖元数据反射的装饰器,但编译器选项未启用 —— 运行时元数据缺失。

为什么发生

  • tsconfig.json 未设置 emitDecoratorMetadata: true,类型元数据未发射

  • experimentalDecorators 选项未启用,这是装饰器支持所必需的

  • reflect-metadata polyfill 未在使用装饰器前于入口点导入

最小示例

✗ 错误代码
// tsconfig.json missing emitDecoratorMetadata
@Injectable()
class MyService {
  constructor(private dep: OtherService) {} // dep type metadata missing
}
✓ 修复代码
// tsconfig.json:
// { "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true } }
import 'reflect-metadata';
@Injectable()
class MyService {
  constructor(private dep: OtherService) {} // metadata available
}

启用 emitDecoratorMetadata 并导入 reflect-metadata 使构造函数参数类型在运行时可用于依赖注入。

如何诊断

  • 检查 tsconfig.json 中 experimentalDecorators 和 emitDecoratorMetadata 是否都为 true

  • 验证 'import reflect-metadata' 在任何装饰器使用前位于入口文件顶部

  • 记录 Reflect.getMetadata('design:paramtypes', target) 查看运行时是否有元数据

如何修复

  • 在 tsconfig.json 中设置 experimentalDecorators: true 和 emitDecoratorMetadata: true

  • 在应用入口点任何装饰器代码之前导入 reflect-metadata polyfill

  • 如果使用打包器,确保它保留装饰器元数据且不 tree-shake reflect-metadata

如何预防

  • 使用装饰器时始终同时启用 experimentalDecorators 和 emitDecoratorMetadata

  • 在入口点导入 reflect-metadata 并确保不被 tree-shaking 移除

相关资源

相关术语

相关课程

← 返回语言