【问题标题】:Angular2 why do we need the es6-shimAngular2 为什么我们需要 es6-shim
【发布时间】:2016-08-26 15:15:20
【问题描述】:

Angular2 Quickstart Guide 之后,我们被指示在两个地方包含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 的填充程序?

【问题讨论】:

    标签: angular es6-shim


    【解决方案1】:

    您的编辑器使用键入来为您提供代码提示/智能感知,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 将是未定义的......

    【讨论】:

    • 你的意思是编辑器给出的hinting/intellisense正在使用es6-shim?
    • 截至 2016 年 10 月,他们现在在 OP 引用的快速入门中推荐 core-js 而不是 es6-shim。
    【解决方案2】:

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

    TypeScript 定义文件将在您选择的编辑器中为您提供打字支持,es-shim 将提供 TypeScript 不会转译为 ES5 代码的功能的实现。

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

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

    一般做法是:

    经验法则是,如果有一个规范/健全的发射没有巨大的性能命中,我们将尝试支持它。我们不添加任何运行时方法或数据结构,这更像是 core.js (或任何 pollyfil) 所要做的。 - source (TypeScript developer)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-27
      • 2019-06-09
      • 2014-06-18
      • 2017-02-26
      • 2011-04-03
      • 2017-07-27
      • 2020-09-21
      • 2020-03-09
      相关资源
      最近更新 更多