nodejs 中的 Typescript Reflect-MetaData
Typescript Reflect-MetaData in nodejs
有没有人有任何关于如何在 nodejs 中使用 reflect-metadata 的例子?我也在使用 atom-typescript。我通过 npm 下载使用它,但我不断收到随机错误。我看到 Reflect 是一个空白对象。只是在寻找如何将其合并到模块或节点项目中的示例。
当我遇到同样的问题但没有任何效果时,我打开了 node_modules 中的 Reflect.ts 文件。最后可以看到它在全局层面hook了Reflect
// hook global Reflect
(function(__global: any) {
if (typeof __global.Reflect !== "undefined") {
if (__global.Reflect !== Reflect) {
for (var p in Reflect) {
__global.Reflect[p] = (<any>Reflect)[p];
}
}
}
else {
__global.Reflect = Reflect;
}
})(
typeof window !== "undefined" ? window :
typeof WorkerGlobalScope !== "undefined" ? self :
typeof global !== "undefined" ? global :
Function("return this;")());
所以,我从所有其他文件中删除了 require reflect-metadata,并将其移至主文件。
require('reflect-metadata/Reflect');
现在,我可以使用以下语法在所有模块中使用它(不需要反射元数据),
(<any>global).Reflect.getMetadata("design:type", target, key); // In Typescript
编辑:
我们也可以从node_modules引用reflect-metadata.d.ts文件,然后直接使用API。
/// <reference path="../../node_modules/reflect-metadata/reflect-metadata.d.ts" />
Reflect.getMetadata("design:type", target, propertyKey);
在TypeScript@2.0+中,可以这样使用:
npm i -S reflect-metadata
npm i -D @types/reflect-metadata
// your.ts
import 'reflect-metadata'
Reflect.getMetadata(...)
Reflect.metadata(...)
有没有人有任何关于如何在 nodejs 中使用 reflect-metadata 的例子?我也在使用 atom-typescript。我通过 npm 下载使用它,但我不断收到随机错误。我看到 Reflect 是一个空白对象。只是在寻找如何将其合并到模块或节点项目中的示例。
当我遇到同样的问题但没有任何效果时,我打开了 node_modules 中的 Reflect.ts 文件。最后可以看到它在全局层面hook了Reflect
// hook global Reflect
(function(__global: any) {
if (typeof __global.Reflect !== "undefined") {
if (__global.Reflect !== Reflect) {
for (var p in Reflect) {
__global.Reflect[p] = (<any>Reflect)[p];
}
}
}
else {
__global.Reflect = Reflect;
}
})(
typeof window !== "undefined" ? window :
typeof WorkerGlobalScope !== "undefined" ? self :
typeof global !== "undefined" ? global :
Function("return this;")());
所以,我从所有其他文件中删除了 require reflect-metadata,并将其移至主文件。
require('reflect-metadata/Reflect');
现在,我可以使用以下语法在所有模块中使用它(不需要反射元数据),
(<any>global).Reflect.getMetadata("design:type", target, key); // In Typescript
编辑: 我们也可以从node_modules引用reflect-metadata.d.ts文件,然后直接使用API。
/// <reference path="../../node_modules/reflect-metadata/reflect-metadata.d.ts" />
Reflect.getMetadata("design:type", target, propertyKey);
在TypeScript@2.0+中,可以这样使用:
npm i -S reflect-metadata
npm i -D @types/reflect-metadata
// your.ts
import 'reflect-metadata'
Reflect.getMetadata(...)
Reflect.metadata(...)