【问题标题】:Add polyfill code in Angular 2在 Angular 2 中添加 polyfill 代码
【发布时间】:2017-02-21 08:16:06
【问题描述】:

如何在 Angular 2 cli 项目中添加 polyfill 的代码?

例如,我想使用来自Mozilla MDN 的以下polyfill:

if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {
      if (this == null) { throw new TypeError('"this" is null or not defined'); }
      var o = Object(this);
      var len = o.length >>> 0;
      if (len === 0) { return false; }
      var n = fromIndex | 0;
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
      while (k < len) {
        if (o[k] === searchElement) { return true; }
        k++;
      }
      return false;
    }
  });
}

我发现另一个线程通过 npm (How to add Web Animations API polyfill to an Angular 2 project created with Angular CLI ) 安装了 polyfill。但是如果没有 npm 包怎么办呢?

【问题讨论】:

  • 是你项目的 core-js 的一部分吗?

标签: angular polyfills


【解决方案1】:

请注意,对于您的个人情况(使用 angular 2,core-js 通常包含在大多数入门包中)。所以你只需要把它添加到你的polyfills.ts:

import "core-js/es7";

但是,如果您对在 typescript 中声明自定义 polyfill 感兴趣,可以查看this question。然后你只需要在polyfills.ts 中require("your-custom-polyfill.js")。

【讨论】:

  • 感谢您的链接。我会尝试这种方法并提供反馈。
  • 好答案。它通常包含在内,但值得一提的是,如果尚未安装它,如何获取它。还要避免使用@types/core-js 包并在tsconfig.json 中使用"lib": ["es2017", "dom"]。它绊倒了很多人。
  • 具体来说,对于 Array.includes 你需要import 'core-js/es7/array'
猜你喜欢
  • 2020-09-07
  • 2020-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多