将Angular 1.x与TypeScript 1.5和SystemJS一起使用

adr*_* h. 8 javascript angularjs typescript ecmascript-6 jspm

我正在尝试使用Typeular 1.5.3和SystemJS的Angular 1.x. index.html页面已设置为System.import('bootstrapper')应该开始的页面.

bootstrapper.tsbootstrapper.js只要它不使用角度(即只做一个console.log()工作正常)编译到并工作正常

现在,我想导入并使用angular来引导它.我已经完成了jspm install angular,我还安装了一些角度使用的打字tsd.bootstrap.ts文件顶部引用了这些类型.

不幸的是,做import angular from 'angular'不编译,我明白了Module "angular" has no default export.我的问题是:

  1. 为什么不import angular from 'angular'编译?查看angular.d.ts文件,我看到declare module 'angular'{ export = angular; }哪个,如果我理解正确,是从变量的模块角度的默认导出(在上面的typing文件中定义)declare var angular: angular.IAngularStatic
  2. 我注意到import 'angular'编译然后我可以实际参考angular并做例如angular.module(...),但我不认为我正确理解这是如何工作的.不应该import 'angular'做"裸导入",即仅为其副作用运行模块?如果是这种情况,这是否意味着此导入实际上angular在全局范围内注册?

我很确定我没有正确理解模块/类型定义文件在Typescript中是如何工作的,提前感谢解释.

Alu*_*dad 7

首先,以下是我使用TypeScript和SystemJS的AngularJS 1.5的首选方法: index.html

<script src="jspm_packages/system.js"></script>
<script src="config.js"></script>

<script>
  SystemJS.import('app')
    .then(function (app) {
      app.bootstrap(document);
    })
    .catch(function (reason) { 
      console.error(reason);
    });
</script>
Run Code Online (Sandbox Code Playgroud)

app/main.ts

import angular from 'angular';

const app = angular.module('app', []);

export function bootstrap(target: Element | Document) {
  angular.bootstrap(target, [app.name], { strictDi: true });
}
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
    "compilerOptions": {
      "module": "system",
      "allowSyntheticDefaultImports": true,
      ....
    }
}
Run Code Online (Sandbox Code Playgroud)

config.js (loader config,简化)

SystemJS.config({
  transpiler: "typescript",
  packages: {
    "app": {
      "main": "main.ts",
      "defaultExtension": "ts",
      "meta": {
        "*.ts": {
          "loader": "typescript"
        }
      }
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. 如果您使用JSPM 0.17指定"plugin-typescript",不是"typescript"为加载器和转换器或只是运行$ jspm init并选择一个转换器.
  2. 您可以将angular作为默认值导入,但它仍会在全局范围内注册.
  3. 您获得语法错误的原因是angular,它的angular.d.ts声明文件包含一个CommonJS样式export =声明,以允许基于模块和全局命名空间的用法.SystemJS为了获得最大兼容性,在运行时将其插入到默认导出中.
  4. 需要让TypeScript编译器意识到这一点.这可以通过设置"module": "system"和/或指定来完成"allowSyntheticDefaultImports": true.我为了阐述和明确而做了两件事.


tho*_*epo 5

[...]如果我理解正确,是从变量的模块角度的默认导出

不,这不是正在发生的事情.如果有意义的话,Angular会将整个命名空间导出为导出.

import angular from 'angular'正在尝试default从模块导入.

你想要的是import * as angular from 'angular';将整个导出作为变量导入.

  • 需要注意的是,`import angular`不会尝试导入名为`angular`的东西,它试图将名为`default`的东西导入名为`angular`的绑定中. (2认同)