Autopolyfiller — Precise polyfills
This is like Autoprefixer, but for JavaScript polyfills
How it works:
- Using AST matchers it scans your code and finds all polyfills
- If target browsers are specified, then it reduces the list of polyfills according to the "feature database"
- It generates polyfills code which precisely fixes only required features
It will not work if:
- You
eval
code with polyfills. Eg eval('Object.keys(this)')
- You doing something odd. Eg
Object['k' + 'eys']()
Installation
autopolyfiller
can be installed using npm
:
npm install autopolyfiller
CLI Example
$ autopolyfiller lib/**/*.js -b "Explorer 7, Chrome >= 10"
$ cat lib/*.js | autopolyfiller
Grunt & Gulp tasks
Example
require('autopolyfiller')().add(code) + code;
List of polyfills without browsers filtering
var autopolyfiller = require('autopolyfiller');
autopolyfiller()
.add('"".trim();')
.polyfills;
Filtering using Autoprefixer-style browser matchers
var autopolyfiller = require('autopolyfiller');
autopolyfiller('IE 11', 'Chrome >= 31')
.add('"".trim();Object.create();new Promise()')
.polyfills;
Default autoprefixer browsers
var autopolyfiller = require('autopolyfiller'),
autoprefixer = require('autopolyfiller');
autopolyfiller(autoprefixer.default)
.add('new Promise();')
.polyfills;
Excluding/including polyfills
var autopolyfiller = require('autopolyfiller'),
autoprefixer = require('autopolyfiller');
autopolyfiller()
.exclude(['Promise'])
.include(['String.prototype.trim'])
.add('new My.Promise();')
.polyfills;
Custom polyfill matchers
var query = require('grasp-equery').query;
var autopolyfiller = require('autopolyfiller');
autopolyfiller.use({
test: function (ast) {
return query('Object.newFeature(_$)', ast).length > 0 ? ['Object.newFeature'] : [];
},
support: {
'Chrome': [{
only: '29',
fill: 'Object.newFeature'
}]
},
polyfill: {
'Object.newFeature': 'Object.newFeature = function () {};'
}
});
autopolyfiller()
.add('Object.create();Object.newFeature();')
.polyfills;
autopolyfiller('Chrome >= 20')
.add('Object.create();Object.newFeature();')
.polyfills;