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 - https://github.com/facebook/codemod#install
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.
componentWillReceiveProps() function will become
componentWillMount() function will become
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 \ 'componentWillReceiveProps' 'UNSAFE_componentWillReceiveProps'
Change componentWillMount to UNSAFE_componentWillMount
codemod -m --extensions js \ 'componentWillMount' 'UNSAFE_componentWillMount'
Change componentWillUpdate to UNSAFE_componentWillUpdate
codemod -m --extensions js \ 'componentWillUpdate' 'UNSAFE_componentWillUpdate'
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
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.