Last active
October 14, 2022 21:04
-
-
Save green3g/1aad302cabe76add0f29804d0c6dfb91 to your computer and use it in GitHub Desktop.
codemod for replacing commonjs with es6 import/export
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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