What is jssg?
JavaScript ast-grep (jssg) is a secure JavaScript runtime for codemods, similar to Node.js. It includes most Node.js globals and modules (for example,fs
, process
) so you can write real-world transformations in JavaScript/TypeScript.
How it works:
- A jssg codemod is a module that
export default
s a function receiving anSgRoot<L>
(the parsed file) and returning astring
(modified code) ornull
/undefined
(no change). Any other return type is a runtime error. - The
codemod:ast-grep
built‑in provides parsing and pattern matching. At runtime it exportsparse
andparseAsync
;SgRoot
andSgNode
are TypeScript types from@codemod.com/jssg-types
that describe the AST API you interact with in the transform. - You express search conditions as ast-grep rule objects (plain JS), traverse nodes, create edits with
node.replace(...)
, and finalize withrootNode.commitEdits(edits)
.
For engine details and built-ins, see Runtime and built-ins in the API reference.
- Patterns: Describe code shapes using ast-grep’s pattern syntax with captures (for example,
$NAME
,$$$ARGS
). - Rules: Compose patterns with
any
,all
,kind
, relational constraints (inside
,has
,precedes
,follows
), and utilities likematches
andconstraints
. - Edits: Build replacements with
node.replace(text)
and apply them withcommitEdits(edits)
. - Lifecycle: Select → Traverse → Capture → Edit → Commit & Return.
You can author rules as plain JavaScript objects. See the ast‑grep rule configuration docs and the jssg API reference.
Build your first codemod
1
Scaffold a jssg package
JavaScript ast-grep (jssg) codemod
when prompted.This will scaffold a new folder with the required files and structure.2
Write a minimal transform (scripts/codemod.ts)
Key concepts:The transform follows this pattern:
- Transform signature:
export default function transform(root, options)
- Edit flow: find nodes → build edits →
commitEdits(edits)
→ return resulting string - Return contract: string → modified (unless equal to input), null/undefined → unmodified; anything else → error
- Type safety: Always check node types before accessing fields
codemod.ts
- If no matches are found, the step is skipped or files are unchanged
- When matches exist, files with changes are updated in-memory and reported in the diff
- Returning the same string results in “unmodified”; returning null/undefined is also treated as “unmodified”
3
Validate & run
Before
After