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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With