emitDecoratorMetadata是一个tsconfig的配置项,它是nestjs实现IOC容器和依赖注入的核心。
在TS里,emitDecoratorMetadata生成元数据主要有以下三种:
design: type 用于 属性的类型元数据
design: paramtypes 用于 构造函数/方法 参数的类型元数据
design: returntype 用于 方法的返回类型元数据
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import 'reflect-metadata'
function classDecorator(target) {}
function parameterDecorator(target, propertyKey, parameterIndex) {}
function propDecorator(target, propertyKey) {}
function methodDecorator(target, propertyKey, descriptor) {}
@classDecorator class Example {
@propDecorator myProperty: string
constructor(@parameterDecorator serviceA: string, @parameterDecorator serviceB: string) {}
@methodDecorator myMethod(): string { return 'hello' } }
const propertyType = Reflect.getMetadata('design:type', Example.prototype, 'myProperty')
console.log('propertyType:', propertyType)
const paramTypes = Reflect.getMetadata('design:paramtypes', Example)
console.log('paramTypes:', paramTypes)
const methodReturnType = Reflect.getMetadata('design:returntype', Example.prototype, 'myMethod')
console.log('methodReturnType:', methodReturnType)
|
我们基于emitDecoratorMetadata生成的数据,就可以知道要注入容器的内容了。