Gathering detailed insights and metrics for jscodeshift
Gathering detailed insights and metrics for jscodeshift
Gathering detailed insights and metrics for jscodeshift
Gathering detailed insights and metrics for jscodeshift
npm install jscodeshift
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
9,363 Stars
540 Commits
481 Forks
97 Watching
6 Branches
182 Contributors
Updated on 28 Nov 2024
Minified
Minified + Gzipped
JavaScript (96.76%)
MDX (3.14%)
TypeScript (0.1%)
Cumulative downloads
Total Downloads
Last day
-10%
1,184,588
Compared to previous day
Last week
0.6%
6,651,490
Compared to previous week
Last month
4.9%
28,351,211
Compared to previous month
Last year
62.2%
325,923,186
Compared to previous year
18
1
4
jscodeshift is a toolkit for running codemods over multiple JavaScript or TypeScript files. It provides:
Get jscodeshift from npm:
$ npm install -g jscodeshift
This will install the runner as jscodeshift
.
Configure VSCode to debug codemods
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.
1const {run: jscodeshift} = require('jscodeshift/src/Runner') 2const path = require('node:path'); 3 4const transformPath = path.resolve('transform.js') 5const paths = ['foo.js', 'bar'] 6const options = { 7 dry: true, 8 print: true, 9 verbose: 1, 10 // ... 11} 12 13const res = await jscodeshift(transformPath, paths, options) 14console.log(res) 15/* 16{ 17 stats: {}, 18 timeElapsed: '0.001', 19 error: 0, 20 ok: 0, 21 nochange: 0, 22 skip: 0 23} 24*/
The transform is simply a module that exports a function of the form:
1module.exports = function(fileInfo, api, options) { 2 // transform `fileInfo.source` here 3 // ... 4 // return changed source 5 return source; 6};
As of v0.6.1, this module can also be written in TypeScript.
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.
1/** 2 * This replaces every occurrence of variable "foo". 3 */ 4module.exports = function(fileInfo, api, options) { 5 return api.jscodeshift(fileInfo.source) 6 .findVariableDeclarators('foo') 7 .renameTo('bar') 8 .toSource(); 9}
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'}
.
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 -v
option to 1
or 2
.
You can collect even more stats via the stats
function as explained above.
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
1 2module.exports = function transformer(file, api, options) { 3 const j = api.jscodeshift; 4 const rootSource = j(file.source); 5 6 // whatever other code... 7 8 return rootSource.toSource(); 9} 10 11// use the flow parser 12module.exports.parser = 'flow';
Example: specifying a custom parser object in the transform file
1 2module.exports = function transformer(file, api, options) { 3 const j = api.jscodeshift; 4 const rootSource = j(file.source); 5 6 // whatever other code... 7 8 return rootSource.toSource(); 9} 10 11module.exports.parser = { 12 parse: function(source) { 13 // return estree compatible AST 14 }, 15};
1$ jscodeshift -t myTransform.js src 2Processing 10 files... 3Spawning 2 workers with 5 files each... 4All workers done. 5Results: 0 errors 2 unmodified 3 skipped 5 ok
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.
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
1// "foo" 2{ 3 type: 'Literal', 4 value: 'foo', 5 raw: '"foo"' 6}
It'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.
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.
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)
:
1// inside a module transform 2var j = jscodeshift; 3// foo(bar); 4var ast = j.callExpression( 5 j.identifier('foo'), 6 [j.identifier('bar')] 7);
The signature of each builder function is best learned by having a look at the definition files or in the babel/types docs.
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:
1// recast 2var ast = recast.parse(src); 3recast.visit(ast, { 4 visitIdentifier: function(path) { 5 // do something with path 6 return false; 7 } 8}); 9 10// jscodeshift 11jscodeshift(src) 12 .find(jscodeshift.Identifier) 13 .forEach(function(path) { 14 // do something with path 15 });
To learn about the provided methods, have a look at the Collection.js and its extensions.
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.
1// Adding a method to all Identifiers 2jscodeshift.registerMethods({ 3 logNames: function() { 4 return this.forEach(function(path) { 5 console.log(path.node.name); 6 }); 7 } 8}, jscodeshift.Identifier); 9 10// Adding a method to all collections 11jscodeshift.registerMethods({ 12 findIdentifiers: function() { 13 return this.find(jscodeshift.Identifier); 14 } 15}); 16 17jscodeshift(ast).findIdentifiers().logNames(); 18jscodeshift(ast).logNames(); // error, unless `ast` only consists of Identifier nodes
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
You may want to change some of the output settings (like setting '
instead of "
).
This can be done by passing config options to recast.
1.toSource({quote: 'single'}); // sets strings to use single quotes in transformed code.
You can also pass options to recast's parse
method by passing an object to
jscodeshift as second argument:
1jscodeshift(source, {...})
More on config options here
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:
/MyTransform.js
/__tests__/MyTransform-test.js
/__testfixtures__/MyTransform.input.js
/__testfixtures__/MyTransform.output.js
A simple example of unit tests is bundled in the sample directory.
The testUtils
module exposes a number of useful helpers for unit testing.
defineTest
Defines a Jest/Jasmine test for a jscodeshift transform which depends on fixtures
1jest.autoMockOff(); 2const defineTest = require('jscodeshift/dist/testUtils').defineTest; 3defineTest(__dirname, 'MyTransform');
An alternate fixture filename can be provided as the fourth argument to defineTest
.
This also means that multiple test fixtures can be provided:
1defineTest(__dirname, 'MyTransform', null, 'FirstFixture'); 2defineTest(__dirname, 'MyTransform', null, 'SecondFixture');
This will run two tests:
__testfixtures__/FirstFixture.input.js
__testfixtures__/SecondFixture.input.js
defineInlineTest
Defines 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 transform
1const defineInlineTest = require('jscodeshift/dist/testUtils').defineInlineTest; 2const transform = require('../myTransform'); 3const transformOptions = {}; 4defineInlineTest(transform, transformOptions, 'input', 'expected output', 'test name (optional)');
defineSnapshotTest
Similar to defineInlineTest
but instead of requiring an output value, it uses Jest's toMatchSnapshot()
1const defineSnapshotTest = require('jscodeshift/dist/testUtils').defineSnapshotTest; 2const transform = require('../myTransform'); 3const transformOptions = {}; 4defineSnapshotTest(transform, transformOptions, 'input', 'test name (optional)');
For more information on snapshots, check out Jest's docs
defineSnapshotTestFromFixture
Similar to defineSnapshotTest
but will load the file using same file-directory defaults as defineTest
1const defineSnapshotTestDefault = require('jscodeshift/dist/testUtils').defineSnapshotTestDefault; 2const transform = require('../myTransform'); 3const transformOptions = {}; 4defineSnapshotTestFromFixture(__dirname, transform, transformOptions, 'FirstFixture', 'test name (optional)');
applyTransform
Executes 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.
1const applyTransform = require('jscodeshift/dist/testUtils').applyTransform; 2const transform = require('../myTransform'); 3const transformOptions = {}; 4const output = applyTransform(transform, transformOptions, 'input');
If you're authoring your transforms and tests using ES modules, make sure to import the transform's parser (if specified) in your tests:
1// MyTransform.js 2export const parser = 'flow' 3export default function MyTransform(fileInfo, api, options) { 4 // ... 5}
1// __tests__/MyTransform-test.js 2import { defineInlineTest } from 'jscodeshift/dist/testUtils 3import * as transform from '../MyTransform 4 5console.log(transform.parser) // 'flow' 6 7defineInlineTest(transform, /* ... */)
To update docs in /docs
, use npm run docs
.
To view these docs locally, use npx http-server ./docs
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.
1{ 2 // Use IntelliSense to learn about possible attributes. 3 // Hover to view descriptions of existing attributes. 4 // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 "version": "0.2.0", 6 "configurations": [ 7 { 8 "type": "pwa-node", 9 "request": "launch", 10 "name": "Debug Transform", 11 "skipFiles": [ 12 "<node_internals>/**" 13 ], 14 "program": "${workspaceRoot}/node_modules/.bin/jscodeshift", 15 "stopOnEntry": false, 16 "args": ["--dry", "--print", "-t", "${input:transformFile}", "--parser", "${input:parser}", "--run-in-band", "${file}"], 17 "preLaunchTask": null, 18 "runtimeExecutable": null, 19 "runtimeArgs": [ 20 "--nolazy" 21 ], 22 "console": "internalConsole", 23 "sourceMaps": true, 24 "outFiles": [] 25 }, 26 { 27 "name": "Debug All JSCodeshift Jest Tests", 28 "type": "node", 29 "request": "launch", 30 "runtimeArgs": [ 31 "--inspect-brk", 32 "${workspaceRoot}/node_modules/jest/bin/jest.js", 33 "--runInBand", 34 "--testPathPattern=${fileBasenameNoExtension}" 35 ], 36 "console": "integratedTerminal", 37 "internalConsoleOptions": "neverOpen", 38 "port": 9229 39 } 40 ], 41 "inputs": [ 42 { 43 "type": "pickString", 44 "id": "parser", 45 "description": "jscodeshift parser", 46 "options": [ 47 "babel", 48 "babylon", 49 "flow", 50 "ts", 51 "tsx", 52 ], 53 "default": "babel" 54 }, 55 { 56 "type": "promptString", 57 "id": "transformFile", 58 "description": "jscodeshift transform file", 59 "default": "transform.js" 60 } 61 ] 62}
Once this has been added to the configuration
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
14 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 10
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
Found 14/22 approved changesets -- score normalized to 6
Reason
6 existing vulnerabilities detected
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More