10

How would I add code of a polyfill in a Angular 2 cli-project?

For example, I would like to use the following polyfill from Mozilla MDN:

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;
    }
  });
}

I found another thread where the polyfill is installed via npm (How to add Web Animations API polyfill to an Angular 2 project created with Angular CLI ). But how to do that if there is no npm package?

Community
  • 1
  • 1
Marcus
  • 161
  • 1
  • 2
  • 12

1 Answers1

7

Note that for your personnal case (using angular 2, core-js is normally included in most starter packs). so you just need to add this to your polyfills.ts:

import "core-js/es7";

However if you are interested in declaring custom polyfills in typescript, you can take a look at this question. You'll just need to require("your-custom-polyfill.js") in polyfills.ts then.

Community
  • 1
  • 1
n00dl3
  • 21,213
  • 7
  • 66
  • 76
  • Thanks for the link. I will try this approach and give feedback. – Marcus Feb 21 '17 at 10:55
  • 1
    Good answer. It is often included true, but it is worth mentioning how to acquire it if it is not already installed. Also avoid the `@types/core-js` package and use `"lib": ["es2017", "dom"]` in `tsconfig.json` instead. It trips up a lot of people. – Aluan Haddad Feb 24 '17 at 07:39
  • 1
    To be specific, for Array.includes you need `import 'core-js/es7/array'` – ElliotSchmelliot May 18 '18 at 19:48