SaltyCrane Blog — Notes on JavaScript and web development

Simple codemod example with jscodeshift

jscodeshift codemods allow refactoring JavaScript or TypeScript code by manipulating the abstract syntax tree.

This is an example showing how to rename variables named foo to bar.

Install jscodeshift

npm install -g jscodeshift

Create an example file to modify

  • create a folder

    mkdir my-project
    cd my-project
  • create an example file, my-file-to-modify.js

    const foo = 1;

Create a transform

create a file my-transform.js

module.exports = function transformer(fileInfo, api) {
  return api
    .forEach(function (path) {
      if ( === "foo") {

Run it

jscodeshift -t my-transform.js ./my-file-to-modify.js

The file my-file-to-modify.js now contains:

const bar = 1;

Another example

This example removes the React JSX element <MyHeader /> and removes the MyHeader import. I'm not sure why, but it added some extra parentheses. Prettier cleaned this up for me, but if you have an improvement, let me know.

// removeMyHeader.js
module.exports = function transformer(file, api) {
  const jscodeshift = api.jscodeshift;

  const withoutElement = jscodeshift(file.source)
    .forEach(function (path) {
      if ( === "MyHeader") {

  const withoutImport = jscodeshift(withoutElement)
    .forEach(function (path) {
      if ( === "MyHeader") {

  return withoutImport;

Here is a command to run it for a React TypeScript codebase:

jscodeshift --parser=tsx --extensions=tsx -t ./removeMyHeader.js ./src

AST Explorer

AST Explorer is a very helpful tool to experiment and learn the API with code completion. Go to and select "jscodeshift" under the "Transform" menu.

lodash error

Error: Cannot find module 'lodash'

When running jscodeshift, I got the above error so I ran npm install -g lodash and this got rid of the error for me.