Angular2 为什么我们需要 es6-shim

Angular2 why do we need the es6-shim

Angular2 Quickstart Guide 之后,我们被指示在 2 个地方包含 es6-shim

1) index.html

<script src="node_modules/es6-shim/es6-shim.min.js"></script>

2) typings.json

"ambientDependencies": {
  "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#6697d6f7dadbf5773cb40ecda35a76027e0783b2"
}

我的印象是我们正在将 es6 代码编译为 es5

配置于tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    ...

如果最终结果是浏览器正在加载 es5,为什么浏览器需要 es6 的垫片?

您的编辑器使用键入来为您提供代码 hinting/intellisense,而 es6-shim.min.js 是为 ES5 浏览器模拟 ES6 功能的代码。其中一些功能是 PromiseArray.from()...

当您的代码被翻译成 ES5 时,您需要包含 es6-shim 以便您可以在其中使用这些新功能...考虑以下 ES6 代码:

let test1 = () => 123 + 456;
let test2 = new Promise((resolve, reject ) => {});

它将被翻译成 ES5 代码:

var test1 = function () { return 123 + 456; };
var test2 = new Promise(function (resolve, reject) { });

但没有 es6-shim Promise 将是未定义的...

TypeScript 没有内置 polyfill。有一些特性它不能转译,这就是像 es-shim 这样的 polyfill 的用武之地。

TypeScript 定义文件将为您在所选编辑器中提供输入支持,es-shim 将为 TypeScript 无法转换为 ES5 代码的功能提供实现。

TypeScript 无法转换的一些此类功能是:

  • 承诺
  • 函数挂在原型对象上(Array.from()Array.of()Number.isInteger() 等)
  • 模块加载

一般做法是:

The rule of thumb is that if there's a canonical/sane emit that doesn't have a huge perf-hit, we'll try to support it. We don't add any runtime methods or data structures, which is more what core.js (or any pollyfil) serves to do. - source (TypeScript developer)