angular需要reflectmetadata.js和emitDecoratorMetadata:true吗?

时间:2017-07-16 07:52:20

标签: angular typescript

package.json

{ "version": "1.0.0",
  "name": "basic-app",
  "devDependencies": { "typescript": "^2.4.1" },
  "dependencies": {
    "@angular/core": "2.4.5",
    "@angular/platform-browser": "2.4.5",
    "@angular/platform-browser-dynamic": "2.4.5",
    "@angular/common": "2.4.5",
    "@angular/compiler": "2.4.5",
    "@angular/http": "2.4.5",
    "rxjs": "5.0.1",
    "zone.js": "^0.7.2",
    "systemjs": "0.19.40",
    "core-js": "^2.4.1"
 }}

tsconfig.json

{ "compilerOptions": {
  "target": "es5",
  "module": "commonjs",
  "moduleResolution": "node",
  "sourceMap": true,
  "experimentalDecorators": true,
  "emitDecoratorMetadata": false, // set to false
  "lib": ["es2015", "dom"],
  "noImplicitAny": true,
  "suppressImplicitAnyIndexErrors": true
}}

index.html

<!DOCTYPE html>
<html>
<head>
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="src/systemjs.config.js"></script>
<script>
    System.import('main').catch(function(err) {
        console.error(err);
    });
</script>
</head>
<body>
   <my-app>Loading</my-app>
</body>
</html>

当我在浏览器中运行代码时,代码似乎工作正常;我没有包含反映metadata.js,也没有在tsconfig.json中包含emitDecoratorMetadata属性;所以reflectmetadata.js和emitDecoratorMetadata在angular2中是可选的吗?请让我知道为什么上面的代码仍然在浏览器中工作。非常感谢任何帮助。

https://embed.plnkr.co/?show=preview&show=app%2Fapp.component.ts角度示例代码不包含反映metadata.js

1 个答案:

答案 0 :(得分:2)

<强> emitDecoratorMetadata

如果您使用类型作为此类令牌,​​则此设置必须设置为true

constructor(dependency: ClassName) {}

如果它设置为true,编译器将生成以下内容:

AppComponent = __decorate([
    core_1.Component({
        selector: 'my-app',
        ...
    }),
    __metadata("design:paramtypes", [core_1.Injector])
                                       ^^^
                         here the type for token is referenced

如果您只使用@Inject()装饰器,那么您不需要emitDecoratorMetadata设置。

反映元数据

这个包本身通常不是必需的,因为它包含在Angular所需的core.js中:

<script src="node_modules/core-js/client/shim.min.js"></script>