-
-
Save georgybu/e8f09049751f9d8975a5a6d7f66fdbc8 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