Angular2:在 MyComponent 上找不到指令注释

Angular2: No Directive annotation found on MyComponent

我正在尝试组装一个小的 angular2 应用程序: 我没有使用 TypeScript,而是使用带有 babel

的常规 ES6

我的文件如下所示:

//mycomponent.js
import { Component, View } from 'angular2/angular2';

@Component({
  selector: 'my-app'
})
@View({
  template: '<h1>My First Angular 2 App</h1>'
})
class MyComponent {
  constructor() {
  }
  get prop() {
    return 'hello';
  }
}

export { MyComponent };


// index.js
import 'zone.js';
import 'reflect-metadata';

import { MyComponent } from './mycomponent';
import { bootstrap } from 'angular2/angular2';

bootstrap(MyComponent);

然后使用启用了两个预设的 babel-loader 使用 webpack 编译它 ['es2015', 'stage-1']

在浏览器中 运行 时会产生以下错误:

EXCEPTION: Error during instantiation of Token Promise!.
ORIGINAL EXCEPTION: No Directive annotation found on MyComponent

我试过向 MyComponent 添加 @Directive() 注解,但没有效果。

回答我自己的问题:

经过一些调查,我发现 Babel 为 annotations/decorators 发出的代码与 TypeScript 发出的代码不同,因此它不能像上面那样使用。

相反,不使用装饰器,可以在 class 上声明静态 属性,这将 return 装饰器实例数组:

class MyComponent {

  ...

  static get annotations() {
    return [
      new Component({
        selector: 'my-app'
      }),
      new View({
        template: '<span>My First Angular 2 App</span>'
      })
    ];
  }
}