【问题标题】:Development on Angular2 with TS but without NPM使用 TS 但没有 NPM 在 Angular2 上开发
【发布时间】:2016-06-07 23:44:45
【问题描述】:

所有指南都建议安装npm,但我正在寻找一种没有它的方法。

There are Angular2 files available,但它们都不是 TypeScript 代码。

那我该怎么办?我需要Angular2.ts 或特定的Angular2-xx.js.d.ts 文件吗?

更新:我已经下载了 Angular2NPM 并获得了完整的源代码树,其中很难找到具体的东西。在 .d.ts 中搜索 Angular2 未返回任何结果。大量的代码集合中有很多 .ts.d.ts 文件。

【问题讨论】:

    标签: javascript angular typescript npm


    【解决方案1】:

    实际上,这些文件是 Angular2 及其依赖项的捆绑版本。它们可以在使用 TypeScript 编写的应用程序中使用。事实上,TypeScript 不能开箱即用地用于浏览器。您必须对它们进行预处理,以便使用 TypeScript 编译器将它们编译成 ES 代码,或者直接使用 TypeScript 库在浏览器中对其进行转译。

    这可以在 SystemJS 中直接通过其transpiler 配置属性进行配置(见下文)。

    首先只需将这些文件添加到您的 HTML 文件中:

    <script src="https://code.angularjs.org/2.0.0-beta.2/angular2-polyfills.js"></script>
    <script src="https://code.angularjs.org/tools/system.js"></script>
    <script src="https://code.angularjs.org/tools/typescript.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.2/Rx.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.2/angular2.dev.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.2/http.dev.js"></script>
    

    如果你想实现一个没有 NPM 的应用程序,你可以在浏览器中编译你的 TypeScript 文件。这是我们使用 plunkr 时的方式。为此,您需要按如下所述配置 SystemJS:

    <script>
      System.config({
        transpiler: 'typescript', 
        typescriptOptions: {
          emitDecoratorMetadata: true
        },
        packages: {
          'app': {
            defaultExtension: 'ts'
          }
        } 
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
    

    小心在app 文件夹下定义您的 TypeScript 文件

    这是一个简单(且完整)的 plunkr,描述了如何做到这一点:https://plnkr.co/edit/vYQPePG4KDoktPoGaxYu?p=info

    你可以下载相应的代码,并在本地使用它的代码和一个像http-server这样的静态HTTP服务器,而不需要使用NPM。这可能是您的用例的一个很好的起点...

    编辑

    如果你的 TypeScript 文件是 VS 编译的,你需要适配 SystemJS 的配置,如下所述:

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

    这样,SystemJS 会在导入时加载您的 JS 文件。例如:System.import('app/boot') 将使用 app/boot.js 而不是 TypeScript

    【讨论】:

    • 我用的是VS,它会自动把.ts转成.js。
    • 太棒了!因此,包括 Angular2 的 JS 文件及其来自 code.angularjs.org 的依赖项,并配置 SystemJS 以使用您编译的 JS 文件,它应该可以工作;-)
    • 但这会导致浏览器内编译,对吗?
    • 是的,你是对的!您需要相应地调整您的 SystemJS 配置以防止这种情况发生。我更新了我的答案...
    • 只需将其添加到script 元素中。该文件将注册 Angular2 模块将能够从您的 TS 文件中导入。这是一个示例:plnkr.co/edit/h1PAHTzxXevPmdi9X5hD?p=info
    猜你喜欢
    • 1970-01-01
    • 2016-06-29
    • 2023-03-13
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 2022-12-28
    • 2017-01-07
    相关资源
    最近更新 更多