Codemods
easily make sweeping changes to your code

Aug 23, 2018

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 / files
  • ast-types - helps us work with an in-memory representation of the AST, using javascript
  • recast - a library that helps read/write AST (using ast-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.

  1. Intro Articles
  2. Documentation
  3. Development Tips
  4. More Resources
Casey's headshot

Hi, I'm Casey!

I'm all about helping people be
happy and effective.

Casey has dual backgrounds in psychology and software development. He is the author of Debugging Your Brain, an applied psychology and self-help book. He has worked in tech for 10+ years in many roles: Product Manager, Engineering Manager, and UX Developer.

Want your team to be the happiest, most effective team around? Casey is uniquely capable of helping transform the culture of your tech team. Your company deserves Casey's support: keynote presentations, workshops, and coaching.