Top Related Projects
A web tool to explore the ASTs generated by various parsers.
JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator
🐠 Babel is a compiler for writing next generation JavaScript.
Prettier is an opinionated code formatter.
Find and fix problems in your JavaScript code.
A small, fast, JavaScript-based JavaScript parser
Quick Overview
JSCodeshift is a toolkit for running codemods over multiple JavaScript or TypeScript files. It provides a simple API for traversing and transforming an abstract syntax tree (AST) of your code, allowing you to make large-scale automated refactoring of your codebase.
Pros
- Powerful and flexible API for code transformation
- Supports both JavaScript and TypeScript
- Can be used with popular testing frameworks like Jest
- Extensive documentation and community support
Cons
- Steep learning curve for complex transformations
- Performance can be slow for large codebases
- Requires understanding of AST structures
- May produce unexpected results if not used carefully
Code Examples
- Simple variable renaming:
export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.Identifier)
.filter(path => path.node.name === 'oldName')
.replaceWith(
path => j.identifier('newName')
)
.toSource();
}
- Converting require statements to import statements:
export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.CallExpression, {
callee: { name: 'require' }
})
.replaceWith(
p => j.importDeclaration(
[j.importDefaultSpecifier(j.identifier(p.node.arguments[0].value))],
j.literal(p.node.arguments[0].value)
)
)
.toSource();
}
- Adding a new method to a class:
export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.ClassBody)
.forEach(path => {
path.node.body.push(
j.methodDefinition(
'method',
j.identifier('newMethod'),
j.functionExpression(
null,
[],
j.blockStatement([
j.returnStatement(j.literal('Hello, World!'))
])
)
)
);
})
.toSource();
}
Getting Started
To use JSCodeshift, first install it globally:
npm install -g jscodeshift
Create a transform file (e.g., transform.js
) with your transformation logic:
export default function transformer(file, api) {
const j = api.jscodeshift;
// Your transformation code here
return j(file.source)
// ... transformations
.toSource();
}
Run the transformation on your codebase:
jscodeshift -t transform.js path/to/your/files
For more detailed information, refer to the official JSCodeshift documentation.
Competitor Comparisons
A web tool to explore the ASTs generated by various parsers.
Pros of AST Explorer
- Interactive web-based interface for exploring and visualizing Abstract Syntax Trees (ASTs)
- Supports multiple parsers and languages, providing a versatile tool for developers
- Allows real-time code transformation and AST manipulation
Cons of AST Explorer
- Primarily focused on exploration and visualization, not designed for large-scale code transformations
- Limited functionality for batch processing or integrating into build pipelines
- Lacks advanced features for creating and managing complex codemods
Code Comparison
AST Explorer (browser-based):
// Input code
const x = 1;
// Transformed AST visualization
{
"type": "Program",
"body": [
{
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": {
"type": "Identifier",
"name": "x"
},
"init": {
"type": "Literal",
"value": 1
}
}
],
"kind": "const"
}
]
}
jscodeshift:
export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.VariableDeclaration)
.replaceWith(
j.variableDeclaration('let', [j.variableDeclarator(j.identifier('x'), j.literal(2))])
)
.toSource();
}
JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator
Pros of recast
- More focused on AST manipulation and code generation
- Maintains original formatting and comments when possible
- Lighter weight and potentially faster for simple transformations
Cons of recast
- Less comprehensive API for complex code transformations
- Fewer built-in utilities for common refactoring tasks
- Smaller community and ecosystem compared to jscodeshift
Code Comparison
recast:
const recast = require('recast');
const ast = recast.parse(code);
ast.program.body[0].declarations[0].init.value = 'new value';
const output = recast.print(ast).code;
jscodeshift:
module.exports = function(fileInfo, api) {
const j = api.jscodeshift;
const root = j(fileInfo.source);
root.find(j.Literal).replaceWith(
path => j.literal('new value')
);
return root.toSource();
};
Both tools allow for AST manipulation, but jscodeshift provides a more declarative API for complex transformations, while recast offers finer control over the output formatting.
🐠 Babel is a compiler for writing next generation JavaScript.
Pros of Babel
- More comprehensive JavaScript transformation capabilities, supporting modern ECMAScript features and custom plugins
- Wider adoption and larger community, leading to better documentation and support
- Integrated with many build tools and frameworks out-of-the-box
Cons of Babel
- Steeper learning curve due to its extensive configuration options and plugin ecosystem
- Potentially slower transformation process for large codebases compared to jscodeshift's focused approach
Code Comparison
Babel configuration:
{
"presets": ["@babel/preset-env"],
"plugins": ["@babel/plugin-transform-arrow-functions"]
}
jscodeshift transformation:
export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.ArrowFunctionExpression)
.replaceWith(path => j.functionExpression(null, path.node.params, path.node.body))
.toSource();
}
Both tools can transform arrow functions to regular functions, but Babel uses a configuration-based approach, while jscodeshift employs a programmatic transformation.
Prettier is an opinionated code formatter.
Pros of Prettier
- Focuses on code formatting and style consistency, making it easier to maintain a uniform codebase
- Supports a wide range of languages and file types, including JavaScript, TypeScript, CSS, and more
- Has a large community and extensive ecosystem of plugins and integrations
Cons of Prettier
- Limited to code formatting and doesn't provide code transformation capabilities
- Less flexibility in customizing formatting rules compared to more powerful AST manipulation tools
- May require additional tools for complex code refactoring tasks
Code Comparison
jscodeshift example:
export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.Identifier)
.replaceWith(
p => j.identifier(p.node.name.toUpperCase())
)
.toSource();
}
Prettier example:
// No equivalent code transformation
// Prettier focuses on formatting existing code
const formattedCode = prettier.format(sourceCode, {
parser: "babel",
semi: false,
singleQuote: true
});
While jscodeshift allows for complex AST transformations, Prettier is designed to format existing code according to predefined style rules. jscodeshift provides more power and flexibility for code modifications, while Prettier excels at maintaining consistent code style across projects.
Find and fix problems in your JavaScript code.
Pros of ESLint
- Widely adopted and integrated into many development workflows
- Extensive rule set for code style and potential errors
- Highly configurable with plugins and custom rules
Cons of ESLint
- Primarily focused on static analysis, not code transformation
- Limited ability to make complex, multi-file changes
Code Comparison
ESLint configuration:
{
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "double"]
}
}
jscodeshift transformation:
export default function(fileInfo, api) {
return api.jscodeshift(fileInfo.source)
.findVariableDeclarators()
.renameTo('newName');
}
Key Differences
- ESLint is primarily used for linting and enforcing code style, while jscodeshift is designed for large-scale code transformations
- ESLint operates on individual files, whereas jscodeshift can handle multi-file transformations
- ESLint provides immediate feedback during development, while jscodeshift is typically used for one-time codebase migrations
Use Cases
- ESLint: Ongoing code quality maintenance, style enforcement, and error prevention
- jscodeshift: API migrations, updating deprecated syntax, and large-scale refactoring projects
Community and Ecosystem
- ESLint has a larger community and more extensive plugin ecosystem
- jscodeshift is more specialized but has strong support for complex AST transformations
A small, fast, JavaScript-based JavaScript parser
Pros of Acorn
- Lightweight and fast JavaScript parser
- Highly extensible with plugins
- Widely used and well-maintained
Cons of Acorn
- Focused solely on parsing, lacks code transformation capabilities
- Requires additional tools for AST manipulation and code generation
Code Comparison
Acorn (parsing JavaScript):
import * as acorn from 'acorn';
const ast = acorn.parse('const x = 42;', { ecmaVersion: 2020 });
jscodeshift (transforming JavaScript):
export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.findVariableDeclarators('x')
.renameTo('y')
.toSource();
}
Key Differences
- Acorn is primarily a JavaScript parser, while jscodeshift is a toolkit for codemods (code transformations)
- jscodeshift provides a higher-level API for AST manipulation and code generation
- Acorn is more suitable for building custom tools and analyzers, while jscodeshift is better for large-scale code modifications
Use Cases
- Acorn: Building linters, custom analyzers, or language tools
- jscodeshift: Automated refactoring, codebase migrations, and large-scale code transformations
Community and Ecosystem
- Both projects have active communities and are widely used in the JavaScript ecosystem
- Acorn has a larger number of third-party plugins and extensions
- jscodeshift is part of the Facebook open-source ecosystem and is often used in conjunction with other Facebook tools
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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)
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 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)
:
// 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:
// 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
// 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 want to change some of the output settings (like setting '
instead of "
).
This can be done by passing config options to recast.
.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:
jscodeshift(source, {...})
More on config options 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:
- The test is located in a subdirectory under the directory the transform itself is located in (eg.
__tests__
) - Test fixtures are located in a
__testfixtures__
directory
This 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
jest.autoMockOff();
const defineTest = require('jscodeshift/dist/testUtils').defineTest;
defineTest(__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:
defineTest(__dirname, 'MyTransform', null, 'FirstFixture');
defineTest(__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
const defineInlineTest = require('jscodeshift/dist/testUtils').defineInlineTest;
const transform = require('../myTransform');
const transformOptions = {};
defineInlineTest(transform, transformOptions, 'input', 'expected output', 'test name (optional)');
defineSnapshotTest
Similar to defineInlineTest
but instead of requiring an output value, it uses Jest's toMatchSnapshot()
const defineSnapshotTest = require('jscodeshift/dist/testUtils').defineSnapshotTest;
const transform = require('../myTransform');
const transformOptions = {};
defineSnapshotTest(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
const defineSnapshotTestDefault = require('jscodeshift/dist/testUtils').defineSnapshotTestDefault;
const transform = require('../myTransform');
const transformOptions = {};
defineSnapshotTestFromFixture(__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.
const applyTransform = require('jscodeshift/dist/testUtils').applyTransform;
const transform = require('../myTransform');
const transformOptions = {};
const output = applyTransform(transform, transformOptions, 'input');
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:
// MyTransform.js
export const parser = 'flow'
export default function MyTransform(fileInfo, api, options) {
// ...
}
// __tests__/MyTransform-test.js
import { defineInlineTest } from 'jscodeshift/dist/testUtils
import * as transform from '../MyTransform
console.log(transform.parser) // 'flow'
defineInlineTest(transform, /* ... */)
Example Codemods
- react-codemod - React codemod scripts to update React APIs.
- js-codemod - Codemod scripts to transform code to next generation JS.
- js-transforms - Some documented codemod experiments to help you learn.
- fix-js - Codemods to fix some ESLint issues
Local Documentation Server
To update docs in /docs
, use npm run docs
.
To view these docs locally, use npx http-server ./docs
VSCode 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.
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "pwa-node",
"request": "launch",
"name": "Debug Transform",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceRoot}/node_modules/.bin/jscodeshift",
"stopOnEntry": false,
"args": ["--dry", "--print", "-t", "${input:transformFile}", "--parser", "${input:parser}", "--run-in-band", "${file}"],
"preLaunchTask": null,
"runtimeExecutable": null,
"runtimeArgs": [
"--nolazy"
],
"console": "internalConsole",
"sourceMaps": true,
"outFiles": []
},
{
"name": "Debug All JSCodeshift Jest Tests",
"type": "node",
"request": "launch",
"runtimeArgs": [
"--inspect-brk",
"${workspaceRoot}/node_modules/jest/bin/jest.js",
"--runInBand",
"--testPathPattern=${fileBasenameNoExtension}"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"port": 9229
}
],
"inputs": [
{
"type": "pickString",
"id": "parser",
"description": "jscodeshift parser",
"options": [
"babel",
"babylon",
"flow",
"ts",
"tsx",
],
"default": "babel"
},
{
"type": "promptString",
"id": "transformFile",
"description": "jscodeshift transform file",
"default": "transform.js"
}
]
}
Once this has been added to the configuration
- Install jscodeshift as a package if you haven't done so already by running the command npm install --save jscodeshift. The debug configuration will not work otherwise.
- Once the jscodeshift local package has been installed, go to the VSCode file tree and select the file on which you want to run the transform. For example, if you wanted to run codemod transforms of foo.js file, you would click on the entry for foo.js file in your project tree.
- Select "Debug Transform" from the debugging menu's options menu.
- Click the "Start Debugging" button on the VSCode debugger.
- You will be then prompted for the name of jscodeshift transform file. Enter in the name of the transform file to use. If no name is given it will default to transform.js
- Select the parser to use from the presented selection list of parsers. The transform will otherwise default to using the babel parser.
- The transform will then be run, stopping at any breakpoints that have been set.
- If there are no errors and the transform is complete, then the results of the transform will be printed in the VSCode debugging console. The file with the contents that have been transformed will not be changed, as the debug configuration makes use the jscodeshift --dry option.
Recipes
Top Related Projects
A web tool to explore the ASTs generated by various parsers.
JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator
🐠 Babel is a compiler for writing next generation JavaScript.
Prettier is an opinionated code formatter.
Find and fix problems in your JavaScript code.
A small, fast, JavaScript-based JavaScript parser
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot