A codemod helps you make sweeping changes to your code in a really straightforward way. React and Ember both use codemods a ton to help make the upgrade path easy.
It’s kinda like changing your code using a regular expression, except way better. Instead of manipulating strings, it’s based on manipulating the Abstract Syntax Tree. To see what an Abstract Syntax Tree (ast) is like, try putting some code into ASTExplorer and see what it spits out!
Some technologies involved:
codemod
- language-agnostic tool to help run ast manipulations on a codebase / filesast-types
- helps us work with an in-memory representation of the AST, using javascriptrecast
- a library that helps read/write AST (usingast-types
) from javascript source code (text)jscodeshift
- a higher-level tool - it helps us use javascript to manipulate the AST (create/edit/delete “ast nodes”)
To write a codemod I use jscodeshift
directly, and it incorporates the rest. I’ve had to read documentation from them all, but I don’t have to import anything specifically from the others.
My Codemod
I made my first codemod this week! It helps ember users migrate away from importing faker
that’s bundled in ember-cli-mirage
to instead import it from faker
directly. I’m so glad we don’t have to edit these 200 files manually. This also helps out the whole Ember community, for when ember-cli-mirage
eventually moves away from having it bundled at all.
https://github.com/caseywatts/ember-cli-mirage-faker-codemod
Getting Started
Here are some helpful references & resources I used to learn how codemods work, and create the one I did.
- Intro Articles
- Tutorial for how to to start making a codemod, and many tips for how to use the AST explorer tool:
- The original Medium article that explains the structure of jscodeshift and how it was designed.
- Documentation
- jscodeshift documentation is in the source files or you can view them as jsdocs (see my pull request for how)
- AST type function signatures are documented in the ast-types repo (the
def
folder). - The
recast
documentation goes throughpath
vsnode
pretty well
- Development Tips
- Test setup documentation in the jscodeshift repo
- To automate test setup (and for npx setup), try codemod-cli
- For sharing your codemod, there are many options, from
npx
to running it with githubusercontent. See my gist about the options
- More Resources
- this “recipe” from the jscodeshift repo
- ember-modules-codemod
- ember-qunit-codemod
- For examples of other codemods, articles, and related tools, check out awesome jscodeshift
I wrote my first codemod this week!!
— Casey Watts! (@kyloma) August 23, 2018
Interested to know how codemods work? Interested to write your own?
I wrote a blog post for you! :D
https://t.co/R8fCZszvnY#emberjs #reactjs #codemod