diff --git a/experimental/babel-preset-env/src/transformPolyfillRequirePlugin.js b/experimental/babel-preset-env/src/transformPolyfillRequirePlugin.js index 41cf8de476..77ba7f86e1 100644 --- a/experimental/babel-preset-env/src/transformPolyfillRequirePlugin.js +++ b/experimental/babel-preset-env/src/transformPolyfillRequirePlugin.js @@ -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); } }); }