Codemods are tools for large scale refactors of codes. It is like search and replace feature but with more functionality. You must have used search-replace features in your editors. You search for something, maybe using regexes, and replace them.


In order to use codemod, follow the installation steps mentioned Source -

In a virtual environment or as admin user

pip install codemod

or system wide with sudo

sudo -H pip install codemod

How does it work?

Some examples are pretty simple. You enter what you need to find, and then enter what you need to replace with.

codemod -m --extensions html '\<title\>?(.*?)\</title\>\' '\<title\>Techdomain | ?(.*?)\</title\>\'

This command will append "Techdomain | " to the title of the html files.

How to refactor large codebase with codemod?

This is where the real use case of codemod is. Say for example you want to upgrade from react 15 to react 16. But some of the lifecycle methods have been depreciated in react 16. So you have to add "UNSAFE_" prefix to the depreciated lifecycle methods make the methods work.

Meaning, componentWillReceiveProps() function will become UNSAFE_componentWillReceiveProps(), componentWillMount() function will become UNSAFE_componentWillMount(), and componentWillUpdate() function will become UNSAFE_componentWillUpdate().  Lets see the codemod script to replace these functions with UNSAFE prefix in all js files.

Change componentWillReceiveProps to UNSAFE_componentWillReceiveProps

codemod -m --extensions js \

Change componentWillMount to UNSAFE_componentWillMount

codemod -m --extensions js \

Change componentWillUpdate to UNSAFE_componentWillUpdate

codemod -m --extensions js \

After running these scripts, the functions will be replaced with UNSAFE prefix in all js files. If you write react classes in jsx files, then you need to change --extensions js to --extensions jsx.

Codemod scripts

So now you must have an understanding of codemod and how to use them. Codemod is useful for libraries too. Whenever a library upgrades with minor breaking changes, the library can give a codemod script so that users can run it on their codebase and upgrade the code. It will result in less error and manual effort.

React uses a different kind of codemod called JSCodeshift to upgrade react applications. Although codemod and jscodeshift both do code modification, thet are not same. Learn about the differences between jscodeshift and codemod.

There are many such jscodeshift scripts available. You can learn more about jscodeshift and scripts which are available.