Angular2 Selector与bundle和ECM6的任何元素都不匹配

Sim*_*ara 11 html javascript angular

我有一个非常简单的angular2项目,配置为与Gulp,Bundle和ECM6一起使用.Bundle将创建一个大文件,其中包含角度加上我的应用程序的翻译ECM5.

<!DOCTYPE html>
<html>
<head>
    <title>Angular 2 Test</title>
    <script src="bundle.js"></script>
</head>

<body>
<mainapp>

</mainapp>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

角度应用程序定义如下:

import {Component, View, bootstrap} from 'angular2/core';

export class mainComponent {
    static get annotations() {
        return [
            new Component({
                selector: 'mainapp'
            }),
            new View({
                template: `<div>Hello!</div>`
            })
        ];
    }
}

bootstrap(mainComponent);
Run Code Online (Sandbox Code Playgroud)

但是当我加载它时,我继续收到错误

"selector 'mainapp' did not match any element"
Run Code Online (Sandbox Code Playgroud)

Sim*_*ara 23

问题是我在HTML中定义组件bundle.js之前就已经包含了mainapp.这解决了这个问题.

<!DOCTYPE html>
<html>
<head>
    <title>Angular 2 Test</title>

</head>

<body>
<mainapp>

</mainapp>
<script src="bundle.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

更新:

<script src="bundle.js" defer></script>
Run Code Online (Sandbox Code Playgroud)

无论元素的顺序如何,似乎也解决了问题.

  • 添加到脚本中的`defer`属性也会有所帮助. (4认同)