Using jscodeshift to make the same code transformations with less boilerplate
In order to create a codemod, we needed to install several dependencies, and boilerplate code for reading, parsing, and writing files.
This is where a more specialized tool like
jscodeshift becomes useful. It's a toolkit for running codemods. It takes care of all the dependencies, and boilerplate for finding, reading, parsing, and writing back to files. It also has some other nice features for working in large codebases, like running a transform in parallel on multiple files, as well as a summary of how many files were changed.
Let's get started by creating a new directory and installing the dependencies.
The only required dependency is
jscodeshift. Prettier was installed again to consistently format code, but that's a "nice to have." The types were also installed since we're using TypeScript.
Creating the transform#
Next, create a new
transform.ts file with the transform boilerplate to work with jscodeshift.
This transform function follows the jscodeshift API, which is a function that is the default export that accepts three arguments. It also supports transforms written in TypeScript with no additional setup (notice we didn't have to install anything except jscodeshift and its types).
Now, this can be executed with the jscodeshift CLI. It has a number of options. The only required option is the path to the files to run the transform on.
The Flash app is a basic setup, so the defaults work well.
The default jscodeshift parser is
babel. The other options are:
tsx. This can be somewhat confusing, because
babylon was the previous name of