百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
J

jscodeshift

> 编程语言
开源

一个 JavaScript 编码模块工具包。

10.0K stars0 点赞2 次浏览
访问官网GitHub

工具介绍

一个 JavaScript 编码模块工具包。

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:

…

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)

javascript
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:

javascript
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.

javascript
/**
 * 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

javascript

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

javascript

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

javascript
// "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, please have a look at [ast-types][].

Builders

To make creating AST nodes a bit simpler and "safer", ast-types defines a couple of builder methods, which are also exposed on jscodeshift.

For example, the following creates an AST equivalent to foo(bar):

javascript
// inside a module transform
var j = jscodeshift;
// foo(bar);
var ast = j.callExpression(
  j.identifier('foo'),
  [j.identifier('bar')]
);

The signature of each builder function is best learned by having a look at the definition files or in the babel/types docs.

Collections and Traversal

In order to transform the AST, you have to traverse it and find the nodes that need to be changed. jscodeshift is built around the idea of collections of paths and thus provides a different way of processing an AST than recast or ast-types.

A collection has methods to process the nodes inside a collection, often resulting in a new collection. This results in a fluent interface, which can make the transform more readable.

Collections are "typed" which means that the type of a collection is the "lowest" type all AST nodes in the collection have in common. That means you cannot call a method for a FunctionExpression collection on an Identifier collection.

Here is an example of how one would find/traverse all Identifier nodes with jscodeshift and with recast:

javascript
// recast
var ast = recast.parse(src);
recast.visit(ast, {
  visitIdentifier: function(path) {
    // do something with path
    return false;
  }
});

// jscodeshift
jscodeshift(src)
  .find(jscodeshift.Identifier)
  .forEach(function(path) {
    // do something with path
  });

To learn about the provided methods, have a look at the Collection.js and its extensions.

Extensibility

jscodeshift provides an API to extend collections. By moving common operators into helper functions (which can be stored separately in other modules), a transform can be made more readable.

There are two types of extensions: generic extensions and type-specific extensions. Generic extensions are applicable to all collections. As such, they typically don't access specific node data, but rather traverse the AST from the nodes in the collection. Type-specific extensions work only on specific node types and are not callable on differently typed collections.

Examples

javascript
// Adding a method to all Identifiers
jscodeshift.registerMethods({
  logNames: function() {
    return this.forEach(function(path) {
      console.log(path.node.name);
    });
  }
}, jscodeshift.Identifier);

// Adding a method to all collections
jscodeshift.registerMethods({
  findIdentifiers: function() {
    return this.find(jscodeshift.Identifier);
  }
});

jscodeshift(ast).findIdentifiers().logNames();
jscodeshift(ast).logNames(); // error, unless `ast` only consists of Identifier nodes

Ignoring files and directories

Sometimes there are files and directories that you want to avoid running transforms on. For example, the node_modules/ directory, where the project's installed local npm packages reside, can introduce bugs if any files in it are accidentally transformed by jscodeshift.

The simplest way to avoid many of these unwanted transforms is to pass jscodeshift the --gitignore flag, which uses the glob patterns specified in your project’s .gitignore file to avoid transforming anything in directories such as node_modules/, dist/, etc. In most cases anything you want git to ignore you proabably are also going to want jscodeshift to ignore as well. Please note that the .gitignore file use will be taken from the current working directory from which jscodeshift is being run.

jscodeshift --gitignore mytransform.js

For more custom ignore functionality, the --ignore-pattern and the --ignore-config arguments can be used.

--ignore-pattern takes a .gitignore format glob pattern that specifies file and directory patterns to ignore

jscodeshift --ignore-pattern="js_configuration_files/**/*” mytransform.js

// More than one ignore
jscodeshift --ignore-pattern="first_ignored_dir/**/*” -—ignore-pattern="second_ignored_dir/**/*” mytransform.js

--ignore-config takes one or more paths to files containing lines with .gitignore format glob patterns.


// note: .gitignore is a random made-up filename extension for this example

jscodeshift --ignore-config="MyIgnoreFile.gitignore" mytransform.js

// More than one ignore file
jscodeshift --ignore-pattern="first_ignore_file.gitignore” --ignore-pattern="second_ignore_file.gitignore” mytransform.js

Passing options to [recast]

You may

Issues· 155 开放

查看全部 Issues在 GitHub 打开
  • #688

    我是否可以在参数前添加 inert inline `commentBlock`?

    更新于 2026年6月27日
  • #500

    将 jscodeshift 更新到最新版本

    discussion更新于 2026年2月23日
  • #669

    流程 / TypeAlias / 插入正在销毁括号

    更新于 2025年8月6日
  • #650

    在 v0.13 之后, JS 文档类型标注移动到了对象内部

    更新于 2025年7月29日
  • #667

    无法在任何导出声明上调用 insertAfter 或 insertBefore

    更新于 2025年7月25日
  • #262

    当输入文件只包含 LF 时, toSource() 会输出 CRLF 回车换行

    bug更新于 2025年5月20日
  • #389

    find 不会遍历 TypeScript 中的 "typeParameters"

    bugupstream更新于 2025年4月11日
  • #663

    找不到

    更新于 2025年4月9日
  • #661

    我找不到它。我甚至找不到它。

    更新于 2025年4月8日
  • #664

    模板文本中带有换行的意外缩进

    更新于 2025年4月1日

> 标签

JavaScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言