Skip to content

Commit

Permalink
Also handle NS imports
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Feb 16, 2021
1 parent 3838678 commit 7b46d50
Showing 1 changed file with 27 additions and 15 deletions.
42 changes: 27 additions & 15 deletions babel.config.js
Expand Up @@ -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,

Expand Down Expand Up @@ -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;
}

Expand All @@ -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();
},
},
};
Expand Down

0 comments on commit 7b46d50

Please sign in to comment.