Skip to content

Commit

Permalink
Fix importing polyfill plugins in the Rollup bundle (#13017)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Mar 22, 2021
1 parent 2b11748 commit 4beca39
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
28 changes: 26 additions & 2 deletions babel.config.js
Expand Up @@ -158,7 +158,7 @@ module.exports = function (api) {

convertESM ? "@babel/proposal-export-namespace-from" : null,
convertESM ? "@babel/transform-modules-commonjs" : null,
convertESM ? pluginNodeImportInterop : null,
convertESM ? pluginNodeImportInteropBabel : pluginNodeImportInteropRollup,
convertESM ? pluginImportMetaUrl : null,

pluginPackageJsonMacro,
Expand Down Expand Up @@ -420,7 +420,7 @@ function pluginPackageJsonMacro({ types: t }) {
}

// Match the Node.js behavior (the default import is module.exports)
function pluginNodeImportInterop({ template }) {
function pluginNodeImportInteropBabel({ template }) {
return {
visitor: {
ImportDeclaration(path) {
Expand Down Expand Up @@ -470,6 +470,30 @@ function pluginNodeImportInterop({ template }) {
};
}

function pluginNodeImportInteropRollup({ types: t }) {
const depsUsing__esModuleAndDefaultExport = [
src => src.startsWith("babel-plugin-polyfill-"),
];

return {
visitor: {
ImportDeclaration(path) {
const { value: source } = path.node.source;
if (depsUsing__esModuleAndDefaultExport.every(test => !test(source))) {
return;
}

const defImport = path
.get("specifiers")
.find(s => s.isImportDefaultSpecifier());
if (!defImport) return;

defImport.replaceWith(t.importNamespaceSpecifier(defImport.node.local));
},
},
};
}

function pluginImportMetaUrl({ types: t, template }) {
const isImportMeta = node =>
t.isMetaProperty(node) &&
Expand Down
14 changes: 14 additions & 0 deletions packages/babel-standalone/test/babel.js
Expand Up @@ -166,6 +166,20 @@ const require = createRequire(import.meta.url);
"function Foo() {\n this instanceof Foo ? this.constructor : void 0;\n}",
);
});

it("useBuiltIns works", () => {
const output = Babel.transform("[].includes(2)", {
sourceType: "module",
presets: [
["env", { useBuiltIns: "usage", corejs: 3, modules: false }],
],
}).code;

expect(output).toMatchInlineSnapshot(`
"import \\"core-js/modules/es.array.includes.js\\";
[].includes(2);"
`);
});
});

describe("custom plugins and presets", () => {
Expand Down

0 comments on commit 4beca39

Please sign in to comment.