Codemods
A program that transforms source code programmatically via its AST — a scripted, repeatable refactor applied across an entire codebase.
Purpose
A codemod parses source code into an AST, transforms it programmatically, and prints it back out — a repeatable, scripted refactor that can be applied consistently across an entire codebase, rather than a manual find-and-replace.
Example
function codemod(sourceCode) {
const ast = parse(sourceCode);
traverse(ast, {
CallExpression(path) {
if (path.node.callee.name === 'oldFunctionName') {
path.node.callee.name = 'newFunctionName';
}
},
});
return generate(ast);
}
Behavior notes
- A trustworthy codemod is tested against fixtures — real or realistic before/after code samples — rather than trusted to work correctly based on the transform logic alone.
- Idempotency matters: running the codemod twice should produce the same result as running it once, so accidentally re-running it causes no harm.
- Rollback guidance (or, ideally, an automated revert) should ship alongside a codemod applied at scale, in case the transformation needs to be undone after discovering an issue.
- A codemod operating on an AST is far more reliable than a text-based find-and-replace, since it understands code structure (won’t match inside a string literal or comment by accident, correctly handles different call styles).
Common mistakes
- Testing a codemod only manually, on a small sample, before running it across an entire codebase.
- Skipping the idempotency check, risking a double-application causing unintended damage if the codemod is accidentally run twice.
Runtime notes
Built on JavaScript/TypeScript AST tooling (Babel, jscodeshift, and similar) — applicable to any codebase in the target language, independent of the runtime the code itself targets.