Fix importing polyfill plugins in the Rollup bundle (#13017)

This commit is contained in:
Nicolò Ribaudo 2021-03-22 14:48:48 +01:00 committed by GitHub
parent 2b11748555
commit 4beca3999e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 2 deletions

View File

@ -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,
@ -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) {
@ -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) &&

View File

@ -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", () => {