【问题标题】:How do you use a bundled Angular 2 application in the browser?如何在浏览器中使用捆绑的 Angular 2 应用程序?
【发布时间】:2016-03-02 01:46:18
【问题描述】:

我尝试将所有 TypeScript 代码编译成一个 Javascript 文件。但是每当我尝试使用 SystemJS 导入该文件时,网页就会卡在loading...

我使用 gulp 将 typescript 文件编译成一个 Javascript 文件,然后复制到 dist 文件夹。

Gulp 任务:

gulp.task("dist:compileTSConcat", function() {
  return gulp.src("./app/**/*.ts")
    .pipe(ts({
      typescript: require('typescript'), // In my package.json I have "typescript": "1.8.2"
      target: 'ES5',
      module: 'system',
      moduleResolution: 'node',
      experimentalDecorators: true,
      emitDecoratorMetadata: true,
      outFile: 'app.js'
    }))
    .pipe(gulp.dest("./dist/"))
})

SystemJS 在网页中导入代码:

...
    <script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.34.4/es6-shim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.23/system-polyfills.js"></script>

    <script src="https://code.angularjs.org/2.0.0-beta.7/angular2-polyfills.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.23/system-register-only.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.7/Rx.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.7/angular2.dev.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.7/router.dev.js"></script>

    <script>
      //System.config({});
      System.import('app.js').then(null, console.error.bind(console));
    </script>
...

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    您应该将您的 JS 文件包含在 script 标记中并导入应用程序的入口点模块:

    <script src="dist/app.js"></script>
    <script>
      System.import('app').then(null, console.error.bind(console));
    </script>
    

    如果您在 app 文件夹下名为 boot.ts 的文件中引导 Angular 2 应用程序。

    【讨论】:

    • 执行此操作后,我收到错误 - EXCEPTION: The selector "just-some-studying" did not match any elements
    • 当你的主组件有一个在主 HTML 页面中找不到的选择器时。您应该在此 HTML 页面中有 &lt;just-some-studying&gt;Loading...&lt;/just-some-studying&gt;
    • 您能告诉我们如何在 HTML 文件中定义您的主要组件吗?
    • 检查您的模板/样式是否正确加载(Devtools>Network),这有时会弄乱解析器。
    • 在 System.import 中将“app/boot”更改为“app”后,我设法修复了它。我还确保所有脚本标签都低于我的选择器标签。谢谢。
    猜你喜欢
    • 2015-05-04
    • 1970-01-01
    • 2018-10-12
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 2019-04-04
    相关资源
    最近更新 更多