如何导入/使用在打字稿中反映
我试图在这个答案中使用代码。 它使用reflection。 这是一个副本:
export function CustomComponent(annotation: any) { return function (target: Function) { var parentTarget = Object.getPrototypeOf(target.prototype).constructor; var parentAnnotations = Reflect.getMetadata('annotations', parentTarget); var parentAnnotation = parentAnnotations[0]; Object.keys(parentAnnotation).forEach(key => { if (isPresent(parentAnnotation[key])) { annotation[key] = parentAnnotation[key]; } }); var metadata = new ComponentMetadata(annotation); Reflect.defineMetadata('annotations', [ metadata ], target); } }
首先,我得到了这两个错误:
Property 'getMetadata' does not exist on type 'typeof Reflect'. Property 'defineMetadata' does not exist on type 'typeof Reflect'.
然后我运行npm install reflect-metadata
,但是我不知道如何使用它。
import { Reflect } from reflect-metadata; Module '".../node_modules/reflect-metadata/index"' has no exported member 'Reflect'.
要么
import { Reflect } from 'reflect-metadata/Reflect'; Cannot find name 'Record'. Type '{}' is not assignable to type 'V'. File '.../node_modules/reflect-metadata/Reflect.ts' is not a module.
要么
import "reflect-metadata" rollup: Treating 'fs' as external dependency bundle update failed: Error transforming .../node_modules/typescript/lib/typescript.js with 'commonjs' plugin: The keyword 'package' is reserved (57066:28) in .../node_modules/typescript/lib/typescript.js
要么
var reflect = require("reflect-metadata"); Cannot find name 'require'.
要么
declare var require: any; var reflect = require("reflect-metadata"); var Reflect = reflect.Reflect; rollup: Treating 'fs' as external dependency bundle update failed: Error transforming .../node_modules/typescript/lib/typescript.js with 'commonjs' plugin: The keyword 'package' is reserved (57066:28) in .../node_modules/typescript/lib/typescript.js
当然,我只是错过了一些愚蠢的东西,甚至是一个错字。 我能做些什么来使用这个代码?
您必须将types声明与(js)库一起导入
npm install @types/reflect-metadata --save npm install reflect-metadata --save
在您的.ts文件中:
import "reflect-metadata";
Typescript使用的模块加载范例与JavaScript有点不同。
假设你有一个模块定义了三个类A
, B
和C
import { A } from "Modulus"
将从模块Modulus
导入类(或函数) A
,并使其在当前模块中可用。 如果Typescript在Modulus
找不到名为A
导出,则会抛出错误。
// Equivalent to the following in JavaScript: // var ModuleNameOfYourChoice = require("Modulus") import * as ModuleNameOfYourChoice from "Modulus"
将导入在Modulus
声明的所有导出,并以名称ModuleNameOfYourChoice
使其可用于当前模块。
对于您的代码,您需要reflect-metadata
模块中定义的所有导出,因此需要将其导入为
import * as Reflect from "reflect-metadata"
祝一切顺利!
Typescript文档: http ://www.typescriptlang.org/docs/handbook/modules.html#import