Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add polyfill code in Angular 2

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?

like image 618
Marcus Avatar asked Feb 21 '17 08:02

Marcus


1 Answers

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.

like image 146
n00dl3 Avatar answered Oct 04 '22 18:10

n00dl3