Skip to content

Instantly share code, notes, and snippets.

@georgybu
Forked from green3g/es6.js
Created October 14, 2022 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgybu/e8f09049751f9d8975a5a6d7f66fdbc8 to your computer and use it in GitHub Desktop.
Save georgybu/e8f09049751f9d8975a5a6d7f66fdbc8 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