Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix importing polyfill plugins in the Rollup bundle #13017

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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