chore: replace micromatch with picomatch
Replace micromatch with picomatch for glob matching in ignoreFiles.js. Only micromatch.isMatch() was used, which maps directly to picomatch.isMatch(). picomatch has no dependencies and a smaller install size (83 kB vs 235 kB).
Closes #603
Co-Authored-By: Claude Opus 4.6 noreply@anthropic.com
版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9
京公网安备 11010802032778号
jscodeshift

jscodeshift is a toolkit for running codemods over multiple JavaScript or TypeScript files. It provides:
Install
Get jscodeshift from npm:
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
-tor--transform(defaults totransform.jsin the current directory). The next section explains the structure of the transform module.Usage (JS)
Transform module
The transform is simply a module that exports a function of the form:
As of v0.6.1, this module can also be written in TypeScript.
Arguments
fileInfoHolds information about the currently processed file.
apiThis object exposes the
jscodeshiftlibrary and helper functions from the runner.--dryrunsjscodeshiftis 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.Note: This API is exposed for convenience, but you don’t have to use it. You can use any tool to modify the source.
statsis a function that only works when the--dryoptions 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).
reportallows you to print arbitrary strings to stdout. This can be useful when other tools consume the output of jscodeshift. The reason to not directly useprocess.stdoutin transform code is to avoid mangled output when many files are processed.optionsContains 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
optionswould contain{foo: 'bar'}.Return value
The return value of the function determines the status of the transformation:
The CLI provides a summary of the transformation at the end. You can get more detailed information by setting the
-voption to1or2.You can collect even more stats via the
statsfunction 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
Example: specifying a custom parser object in the transform file
Example output
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
Literalnodes, which have the structureIt’s OK to not know the structure of every AST node type. The (esprima) 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):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
FunctionExpressioncollection on anIdentifiercollection.Here is an example of how one would find/traverse all
Identifiernodes with jscodeshift and with recast: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
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.
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
–ignore-config takes one or more paths to files containing lines with .gitignore format glob patterns.
Passing options to recast
You may want to change some of the output settings (like setting
'instead of"or changing the end-of-line terminator to\r\nfor Windows files). This can be done by passing config options to recast.You can also pass options to recast’s
parsemethod by passing an object to jscodeshift as second argument:For more details on recast config options, see here.
Unit Testing
jscodeshift comes with a simple utility to allow easy unit testing with Jest, without having to write a lot of boilerplate code. This utility makes some assumptions in order to reduce the amount of configuration required:
__tests__)__testfixtures__directoryThis results in a directory structure like this:
A simple example of unit tests is bundled in the sample directory.
The
testUtilsmodule exposes a number of useful helpers for unit testing.defineTestDefines a Jest/Jasmine test for a jscodeshift transform which depends on fixtures
An alternate fixture filename can be provided as the fourth argument to
defineTest. This also means that multiple test fixtures can be provided:This will run two tests:
__testfixtures__/FirstFixture.input.js__testfixtures__/SecondFixture.input.jsdefineInlineTestDefines a Jest/Jasmine test suite for a jscodeshift transform which accepts inline values
This is a more flexible alternative to
defineTest, as this allows to also provide options to your transformdefineSnapshotTestSimilar to
defineInlineTestbut instead of requiring an output value, it uses Jest’stoMatchSnapshot()For more information on snapshots, check out Jest’s docs
defineSnapshotTestFromFixtureSimilar to
defineSnapshotTestbut will load the file using same file-directory defaults asdefineTestapplyTransformExecutes your transform using the options and the input given and returns the result. This function is used internally by the other helpers, but it can prove useful in other cases. (bear in mind the
transformmodule can be asynchronous. In that case,applyTransformwill return aPromisewith the transformed code. Otherwise, it will directly return the transformed code as astring).ES modules
If you’re authoring your transforms and tests using ES modules, make sure to import the transform’s parser (if specified) in your tests:
Example Codemods
Local Documentation Server
To update docs in
/docs, usenpm run docs.To view these docs locally, use
npx http-server ./docsVSCode Debugging
It’s recommended that you set up your codemod project to all debugging via the VSCode IDE. When you open your project in VSCode, add the following configuration to your launch.json debugging configuration.
Once this has been added to the configuration
Recipes