Skip to content

Instantly share code, notes, and snippets.

@developit
Created April 10, 2020 20:12
Show Gist options
  • Save developit/3e38560d5bed35da1fd708d635e4acb3 to your computer and use it in GitHub Desktop.
Save developit/3e38560d5bed35da1fd708d635e4acb3 to your computer and use it in GitHub Desktop.
module.exports = function (babel) {
const t = babel.types;
const importTpl = babel.template('const SPECIFIERS = require(SOURCE)');
const exportTpl = babel.template('module.exports = EXPORT');
return {
name: 'transform-modules-commonjs-simplified',
visitor: {
ImportDeclaration(path) {
const specs = path.node.specifiers;
let specifiers;
if (specs.length === 1 && t.isImportDefaultSpecifier(specs[0])) {
specifiers = t.clone(specs[0].local);
}
else {
specifiers = babel.types.objectPattern(
specs.map(s => t.objectProperty(
s.local,
s.imported || t.identifier('default'),
false,
true
))
);
}
path.replaceWith(importTpl({
SPECIFIERS: specifiers,
SOURCE: t.clone(path.node.source)
}));
},
ExportDefaultDeclaration(path) {
path.replaceWith(exportTpl({
EXPORT: t.clone(path.node.declaration)
}));
}
}
};
};
{
"name": "babel-plugin-commonjs-lite",
"version": "0.1.0",
"main": "babel-plugin-commonjs-lite.js",
"license": "MIT"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment