diff --git a/babel.config.js b/babel.config.js index 5aaffb7bc732..6fdc3945f374 100644 --- a/babel.config.js +++ b/babel.config.js @@ -125,7 +125,7 @@ module.exports = function (api) { convertESM ? "@babel/proposal-export-namespace-from" : null, convertESM ? "@babel/transform-modules-commonjs" : null, - convertESM ? pluginDefaultImportNode : null, + convertESM ? pluginNodeImportInterop : null, pluginPackageJsonMacro, @@ -385,15 +385,12 @@ function pluginPackageJsonMacro({ types: t }) { } // Match the Node.js behavior (the default import is module.exports) -function pluginDefaultImportNode({ types: t }) { +function pluginNodeImportInterop({ template }) { return { visitor: { ImportDeclaration(path) { const specifiers = path.get("specifiers"); - if ( - specifiers.length === 0 || - !specifiers[0].isImportDefaultSpecifier() - ) { + if (specifiers.length === 0) { return; } @@ -407,16 +404,31 @@ function pluginDefaultImportNode({ types: t }) { return; } - path.insertAfter( - t.variableDeclaration("const", [ - t.variableDeclarator( - specifiers[0].node.local, - t.callExpression(t.identifier("require"), [path.node.source]) - ), - ]) - ); + const defImport = specifiers.find(s => s.isImportDefaultSpecifier()); + const nsImport = specifiers.find(s => s.isImportNamespaceSpecifier()); + + if (defImport) { + path.insertAfter( + template.ast` + const ${defImport.node.local} = require(${source}); + ` + ); + defImport.remove(); + } + + if (nsImport) { + path.insertAfter( + template.ast` + const ${nsImport.node.local} = { + ...require(${source}), + default: require(${source}), + }; + ` + ); + nsImport.remove(); + } - specifiers[0].remove(); + if (path.node.specifiers.length === 0) path.remove(); }, }, };