【问题标题】:How to compile an Angular2 TypeScript application to a single file?如何将 Angular2 TypeScript 应用程序编译为单个文件?
【发布时间】:2015-10-18 17:30:03
【问题描述】:

我意识到我可以使用tsc my_app.ts --target system 编译我的应用程序,它会为每个导入的模块生成一个 SystemJS 包装的文件,这很棒,但它会生成匿名(无名)函数,所以我不能只是连接它们到单个文件。

我想过提出这个问题“如何将 TypeScript 编译为命名的 SystemJS 模块”,但我的目标只是将我的 Angular2 应用程序编译为单个文件,不管是否是 SystemJS。

【问题讨论】:

  • @EricMartinez 不幸的是,--out/--outFile 选项不适用于 --module 选项(例如,如果您有导入)github.com/Microsoft/TypeScript/issues/1544
  • 我已经发布了一个更新的答案,因为 TypeScript 在 1.8 版中添加了这个功能

标签: typescript commonjs angular systemjs tsc


【解决方案1】:

自 TypeScript 1.8 起,--outFile 选项与 --module 选项(适用于 AMD 和 SystemJS)一起使用,因此可以本机完成。 Here's the changelog。 TypeScript 还会自动拉取所有不存在于外部模块中的依赖项,因此只编译主应用程序文件就足够了。

如果 Angular 2 没有从 SystemJS 切换,将应用程序捆绑在单个文件中的方法应该像使用 tsc app.ts --target ES5 --module system --experimentalDecorators --moduleResolution node --emitDecoratorMetadata --outFile app.js 之类的选项编译它一样简单

之后应该可以通过以下方式引导应用程序:

<script src="/bower_components/system.js/dist/system-register-only.js"></script>
<script src="/node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="/app.js"></script>
<script>
    System.import('app');
</script>

【讨论】:

  • 我们不能在tsconfig.json 文件中这样做吗?
【解决方案2】:

对于网络:

  1. 使用 TypeScript 编译器编译成 JavaScript。
  2. 在 JavaScript 上使用 browserify 将其合并到一个文件中。

一个更简单的方法是使用tsify。这是一个可以编译 TypeScript 的 browserify 插件。

【讨论】:

    【解决方案3】:

    你需要告诉你 tsc 编译器在 tsc 编译之后把你的 js 文件放在哪里(命令:tsc -w)。 tsconfig.js 文件中的两个参数告诉 TypeScript 编译器将所有 js 输出放到一个目录中的一个文件中是

    "outDir":"dist/",
    "outFile": "dist/app.js"
    

    我的完整 tsconfig.js 如下

    {
      "compilerOptions": {
        "target": "es5",
        "module": "system",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true,
        "outDir":"dist/",
        "outFile": "dist/app.js"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-29
      • 2017-02-12
      • 2012-10-07
      • 2016-12-05
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-23
      相关资源
      最近更新 更多