Jscodeshift
A JavaScript codemod toolkit.
Install / Use
/learn @facebook/JscodeshiftREADME
jscodeshift

jscodeshift is a toolkit for running codemods over multiple JavaScript or TypeScript files. It provides:
- A runner, which executes the provided transform for each file passed to it. It also outputs a summary of how many files have (not) been transformed.
- A wrapper around [recast][], providing a different API. Recast is an AST-to-AST transform tool and also tries to preserve the style of original code as much as possible.
Install
Get jscodeshift from npm:
$ npm install -g jscodeshift
This will install the runner as jscodeshift.
VSCode Debugger
Configure VSCode to debug codemods
Usage (CLI)
See the website for full documentation.
The CLI provides the following options:
$ jscodeshift --help
Usage: jscodeshift [OPTION]... PATH...
or: jscodeshift [OPTION]... -t TRANSFORM_PATH PATH...
or: jscodeshift [OPTION]... -t URL PATH...
or: jscodeshift [OPTION]... --stdin < file_list.txt
Apply transform logic in TRANSFORM_PATH (recursively) to every PATH.
If --stdin is set, each line of the standard input is used as a path.
Options:
"..." behind an option means that it can be supplied multiple times.
All options are also passed to the transformer, which means you can supply custom options that are not listed here.
--(no-)babel apply babeljs to the transform file
(default: true)
-c, --cpus=N start at most N child processes to process source files
(default: max(all - 1, 1))
-d, --(no-)dry dry run (no changes are made to files)
(default: false)
--extensions=EXT transform files with these file extensions (comma separated list)
(default: js)
-h, --help print this help and exit
--ignore-config=FILE ... ignore files if they match patterns sourced from a configuration file (e.g. a .gitignore)
--ignore-pattern=GLOB ... ignore files that match a provided glob expression
--(no-)gitignore adds entries the current directory's .gitignore file
(default: false)
--parser=babel|babylon|flow|ts|tsx the parser to use for parsing the source files
(default: babel)
--parser-config=FILE path to a JSON file containing a custom parser configuration for flow or babylon
-p, --(no-)print print transformed files to stdout, useful for development
(default: false)
--(no-)run-in-band run serially in the current process
(default: false)
-s, --(no-)silent do not write to stdout or stderr
(default: false)
--(no-)stdin read file/directory list from stdin
(default: false)
-t, --transform=FILE path to the transform file. Can be either a local path or url
(default: ./transform.js)
-v, --verbose=0|1|2 show more information about the transform process
(default: 0)
--version print version and exit
--fail-on-error return a 1 exit code when errors were found during execution of codemods
This passes the source of all passed through the transform module specified
with -t or --transform (defaults to transform.js in the current
directory). The next section explains the structure of the transform module.
Usage (JS)
const {run: jscodeshift} = require('jscodeshift/src/Runner')
const path = require('node:path');
const transformPath = path.resolve('transform.js')
const paths = ['foo.js', 'bar']
const options = {
dry: true,
print: true,
verbose: 1,
// ...
}
const res = await jscodeshift(transformPath, paths, options)
console.log(res)
/*
{
stats: {},
timeElapsed: '0.001',
error: 0,
ok: 0,
nochange: 0,
skip: 0
}
*/
Transform module
The transform is simply a module that exports a function of the form:
module.exports = function(fileInfo, api, options) {
// transform `fileInfo.source` here
// ...
// return changed source
return source;
};
As of v0.6.1, this module can also be written in TypeScript.
Arguments
fileInfo
Holds information about the currently processed file.
Property | Description ------------|------------ path | File path source | File content
api
This object exposes the jscodeshift library and helper functions from the
runner.
Property | Description
------------|------------
jscodeshift | A reference to the jscodeshift library
stats | A function to collect statistics during --dry runs
report | Prints the passed string to stdout
jscodeshift is a reference to the wrapper around recast and provides a
jQuery-like API to navigate and transform the AST. Here is a quick example,
a more detailed description can be found below.
/**
* This replaces every occurrence of variable "foo".
*/
module.exports = function(fileInfo, api, options) {
return api.jscodeshift(fileInfo.source)
.findVariableDeclarators('foo')
.renameTo('bar')
.toSource();
}
Note: This API is exposed for convenience, but you don't have to use it. You can use any tool to modify the source.
stats is a function that only works when the --dry options is set. It accepts
a string, and will simply count how often it was called with that value.
At the end, the CLI will report those values. This can be useful while developing the transform, e.g. to find out how often a certain construct appears in the source(s).
report allows you to print arbitrary strings to stdout. This can be
useful when other tools consume the output of jscodeshift. The reason to not
directly use process.stdout in transform code is to avoid mangled output when
many files are processed.
options
Contains all options that have been passed to runner. This allows you to pass additional options to the transform. For example, if the CLI is called with
$ jscodeshift -t myTransforms fileA fileB --foo=bar
options would contain {foo: 'bar'}.
Return value
The return value of the function determines the status of the transformation:
- If a string is returned and it is different from passed source, the transform is considered to be successful.
- If a string is returned but it's the same as the source, the transform is considered to be unsuccessful.
- If nothing is returned, the file is not supposed to be transformed (which is ok).
The CLI provides a summary of the transformation at the end. You can get more
detailed information by setting the -v option to 1 or 2.
You can collect even more stats via the stats function as explained above.
Parser
The transform file can let jscodeshift know with which parser to parse the source files (and features like templates).
To do that, the transform module can export parser, which can either be one
of the strings "babel", "babylon", "flow", "ts", or "tsx",
or it can be a parser object that is compatible with recast and follows the estree spec.
Example: specifying parser type string in the transform file
module.exports = function transformer(file, api, options) {
const j = api.jscodeshift;
const rootSource = j(file.source);
// whatever other code...
return rootSource.toSource();
}
// use the flow parser
module.exports.parser = 'flow';
Example: specifying a custom parser object in the transform file
module.exports = function transformer(file, api, options) {
const j = api.jscodeshift;
const rootSource = j(file.source);
// whatever other code...
return rootSource.toSource();
}
module.exports.parser = {
parse: function(source) {
// return estree compatible AST
},
};
Example output
$ jscodeshift -t myTransform.js src
Processing 10 files...
Spawning 2 workers with 5 files each...
All workers done.
Results: 0 errors 2 unmodified 3 skipped 5 ok
The jscodeshift API
As already mentioned, jscodeshift also provides a wrapper around [recast][]. In order to properly use the jscodeshift API, one has to understand the basic building blocks of recast (and ASTs) as well.
Core Concepts
AST nodes
An AST node is a plain JavaScript object with a specific set of fields, in
accordance with the [Mozilla Parser API][]. The primary way to identify nodes
is via their type.
For example, string literals are represented via Literal nodes, which
have the structure
// "foo"
{
type: 'Literal',
value: 'foo',
raw: '"foo"'
}
It's OK to not know the structure of every AST node type. The [(esprima) AST explorer][ast-explorer] is an online tool to inspect the AST for a given piece of JS code.
Path objects
Recast itself relies heavily on [ast-types][] which defines methods to traverse the AST, access node fields and build new nodes. ast-types wraps every AST node into a path object. Paths contain meta-information and helper methods to process AST nodes.
For example, the child-parent relationship between two nodes is not explicitly
defined. Given a plain AST node, it is not possible to traverse the tree up.
Given a path object however, the parent can be traversed to via path.parent.
For more information about the path object API, pleas
