Add polyfill code in Angular 2

Marcus picture Marcus · Feb 21, 2017 · Viewed 14.8k times · Source

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?

Answer

n00dl3 picture n00dl3 · Feb 21, 2017

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.