jscodeshift and codemods

JS Code Shift

JS Code shift is a toolkit for running codemods, codemods are transforms that take existing code file(s) and produces new code. That is a codemod in the simplest form. I like to think if them as find and replace script on steroids. JS code shift created by Facebook provides 2 things:

  • Runner: The runner executes the transform scripts and provides feedback on the files changed
  • A wrapper for recast, recast is a AST-to-AST tool. Recast is used to preserve the style and syntax of the code that was transformed.

The pattern for running a codemod is to provide the transform path then path to the file(s) that you wish to transform.

 


jscodeshift -t path-to-codemod path-to-code 

 

You can also provide additional options to help with the process e.g. -d for a dry run if you want to test without making changes. -p to print detailed info on the process. JS Code Shift provides an API for transforms

 


module.exports = function(fileInfo, api) {
  return api.jscodeshift(fileInfo.source)
    .findVariableDeclarators('foo')
    .renameTo('bar')
    .toSource();
}

This example taken from the repo, shows how you can easily replace all occurrences of a foo variable with bar. The above transform get passed the file and the JS Code Shift API. This is then used to get the file source and from here there are methods to get different parts of the file e.g. findVariableDeclarators.

 

CodeMods

JS Code Shift provides an extremely powerful toolkit but the true power lives in the code mods that have been created.  I have managed to find some from quick googling, the reactjs community repo holds a collection react code mods. With react being a fast paced and evolving library code mods really help to evolve an existing code base to new patterns and methodologies. Pattern changes such as React.render to ReactDOM.render, in react 0.14 the render method was moved to the react-dom package. Instead of manually changing all your files you could use the code mod. Other code mods are provided such as  manual-bind-t0-arrow which replaces all manuall function binding to use ES6 arrow functions which scopes the functions.

Code Mods are not only just for react they can be run on any JavaScript code, such as a code mod to help migration to ES6. Removing all var’s and replacing with let or const can be a challenge when you have a large code base but running a code mod makes the process quick and painless.

Taking old ES5 code using var’s

Running the codemod:

Resulting code:

We can see here that the codemod has checked the code and determined that the new source should have one let and two const’s.  However nothing is ever perfect and we could say that the const for myObj should be a let, although the code is still technically valid.

 

You can find more codes mods in the following repos:

 

chrislaughlin

 

Leave a Reply

Your email address will not be published. Required fields are marked *