jscodeshift

17.3.0 · active · verified Sun Apr 19

jscodeshift is a powerful toolkit for automating code transformations (codemods) across JavaScript and TypeScript projects. It operates by parsing source code into an Abstract Syntax Tree (AST), allowing programmatic manipulation, and then printing the modified AST back into code. The current stable version is 17.3.0, released in early 2026. While lacking a fixed release cadence, the project is actively maintained, with frequent minor and patch updates primarily driven by `recast` dependency bumps to support new language features (e.g., recent TypeScript syntax) and address parsing quirks. A significant version jump from `v0.x` to `v17.0.0` occurred in August 2024, signaling its maturity rather than a traditional `1.0` release. Its core strength lies in its tight integration with `recast`, which excels at preserving original code formatting, comments, and whitespace, minimizing disruption to a codebase's aesthetics during large-scale refactors. It offers a robust CLI runner for applying transforms to files and an intuitive API for writing complex, style-preserving codemods.

Common errors

Warnings

Install

Imports

Quickstart

This TypeScript quickstart demonstrates a basic codemod that updates `var` declarations to `let` or `const` based on a simplistic immutability check, then shows how to execute it via the `jscodeshift` CLI.

// transform.ts
import type { API, FileInfo, Options } from 'jscodeshift';

/**
 * A simple codemod that transforms `var` declarations to `let` or `const`.
 * It will use `const` if all declarators are simple literals, otherwise `let`.
 */
export default function transformer(file: FileInfo, api: API, options: Options): string | null {
  const j = api.j;
  const root = j(file.source);

  let changed = false;

  root
    .find(j.VariableDeclaration, { kind: 'var' })
    .forEach((path) => {
      const declarations = path.node.declarations;
      // A simplistic check to determine if all declarations are immutable literals
      const allAreConstants = declarations.every(decl =>
        j.match(decl, { id: j.Identifier, init: j.Literal }) && decl.init !== null
      );

      if (allAreConstants) {
        path.node.kind = 'const';
      } else {
        path.node.kind = 'let';
      }
      changed = true;
    });

  // Only return the source if changes were made, otherwise return null
  return changed ? root.toSource() : null;
}

// To run this codemod on a file named `my-code.js`:
// 1. Save the above code as `transform.ts`.
// 2. Ensure `jscodeshift` is installed globally or locally.
//    `npm install -g jscodeshift`
// 3. Execute the codemod:
//    `jscodeshift -t ./transform.ts ./my-code.js --parser=ts`

view raw JSON →