π Codemods bravely make sweeping changes to your code
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!!
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β Casey Watts! (@kyloma) August 23, 2018