plugin transforms the imports/requires

This commit is contained in:
Henry Zhu 2016-12-02 15:33:27 -05:00
parent 6c58d93602
commit c09532f035

View File

@ -1,30 +1,30 @@
// Should throw if no babel-polyfill import is found in all files
// or if more than one is found
// const builtIns = require('../data/builtIns.json');
const builtIns = {
"typed/int8-array": {
"chrome": 5,
"opera": 12,
"firefox": 4,
"safari": 5,
"node": 0.12,
"ie": 10,
"android": 4,
"ios": 6
}
};
const polyfillSource = "babel-polyfill";
let numPolyfillImports = 0;
export default function ({ types: t }) {
function checkNumPolyfillImports() {
numPolyfillImports++;
if (numPolyfillImports > 1) {
console.log("multiple babel-polyfill imports found");
//throw new Error("multiple babel-polyfill imports found");
}
return numPolyfillImports > 1;
}
function addImport(polyfill) {
let declar = t.importDeclaration([], t.stringLiteral(`core-js/fn/${polyfill}`));
declar._blockHoist = 3;
return declar;
}
function addRequire(polyfill) {
return t.expressionStatement(
t.callExpression(
t.identifier("require"),
[
t.stringLiteral(`core-js/modules/${polyfill}`)
]
)
);
}
function isRequire(path, source) {
@ -41,19 +41,33 @@ export default function ({ types: t }) {
ImportDeclaration(path, state) {
if (path.node.specifiers.length === 0 &&
path.node.source.value === polyfillSource) {
checkNumPolyfillImports();
if (checkNumPolyfillImports()) {
path.remove();
return;
}
// change
// path.node.source.value = "changed";
let imports = state.opts.polyfills.map((p) => addImport(p));
path.replaceWithMultiple(imports);
}
},
Program(path, state) {
if (!state.opts.polyfills) {
throw path.buildCodeFrameError(`
"polyfills" option not correctly passed
to the transform-polyfill-require plugin
in babel-preset-env
`);
}
path.get("body").forEach((bodyPath) => {
if (isRequire(bodyPath, polyfillSource)) {
checkNumPolyfillImports();
if (checkNumPolyfillImports()) {
path.remove();
return;
}
// change
// bodyPath.node.expression.arguments[0].value = "changed";
let requires = state.opts.polyfills.map((p) => addRequire(p));
bodyPath.replaceWithMultiple(requires);
}
});
}