Skip to content

Instantly share code, notes, and snippets.

@green3g
Last active October 14, 2022 21:04
Show Gist options
  • Save green3g/1aad302cabe76add0f29804d0c6dfb91 to your computer and use it in GitHub Desktop.
Save green3g/1aad302cabe76add0f29804d0c6dfb91 to your computer and use it in GitHub Desktop.
codemod for replacing commonjs with es6 import/export
const requireRegex = new RegExp(/(?:var|let|const)?\s*([^\s]+)?(\s*=\s*)?require\s*\(['"](.+)['"]\)[;,]?/, 'g');
const importReplace = "import $1 from '$3';";
const exportsRegex = new RegExp(/module.exports\s*=\s*/, 'g');
const exportReplace = "export default ";
const importMissingVariable = new RegExp(/import\s*from\s*'/, 'g');
const replaceMissingVariable = "import '";
const requireOrExportsRegex = new RegExp(/[require|exports]/);
function shouldReplace(text){
return requireOrExportsRegex.test(text);
}
module.exports = function transformer(file, api) {
let src = file.source;
try {
if(!shouldReplace(src)){
return src;
}
src = src.replace(requireRegex, importReplace)
.replace(exportsRegex, exportReplace)
.replace(importMissingVariable, replaceMissingVariable)
} catch(e) {
console.error(e);
}
return src;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment