diff --git a/babel.config.js b/babel.config.js index d6a7cc57cf..4e20f51e30 100644 --- a/babel.config.js +++ b/babel.config.js @@ -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) && diff --git a/packages/babel-standalone/test/babel.js b/packages/babel-standalone/test/babel.js index 6bb1307a06..32fd928921 100644 --- a/packages/babel-standalone/test/babel.js +++ b/packages/babel-standalone/test/babel.js @@ -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", () => {