JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator
npx @tessl/cli install tessl/npm-recast@0.23.0Recast is a JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator. It enables parsing JavaScript/TypeScript code into Abstract Syntax Trees (ASTs), performing transformations while preserving original formatting for unchanged code, and generating high-resolution source maps automatically.
npm install recastimport { parse, print, prettyPrint, types, visit, run } from "recast";For CommonJS:
const { parse, print, prettyPrint, types, visit, run } = require("recast");import { parse, print, types } from "recast";
// Parse source code into an AST
const code = `
function add(a, b) {
return a + b;
}`;
const ast = parse(code);
// Transform the AST using ast-types builders
const b = types.builders;
ast.program.body[0] = b.variableDeclaration("const", [
b.variableDeclarator(
b.identifier("add"),
b.functionExpression(null, ast.program.body[0].params, ast.program.body[0].body)
)
]);
// Print back to source code, preserving original formatting where unchanged
const result = print(ast);
console.log(result.code);Recast is built around several key components:
.original property references for tracking changesEssential functions for parsing source code into ASTs and reprinting modified ASTs back to source code.
function parse(source: string, options?: Options): types.ASTNode;
function print(node: types.ASTNode, options?: Options): PrintResultType;
function prettyPrint(node: types.ASTNode, options?: Options): PrintResultType;Preconfigured parsers for different JavaScript dialects and advanced parser configuration options.
interface Options {
parser?: any;
tabWidth?: number;
useTabs?: boolean;
reuseWhitespace?: boolean;
sourceFileName?: string;
sourceMapName?: string;
// ... many more options
}Tools for traversing and modifying Abstract Syntax Trees with type safety.
function visit(ast: types.ASTNode, visitor: Visitor): types.ASTNode;
interface Visitor {
[key: string]: (path: NodePath) => any;
}Automatic source map generation for tracking original source locations through transformations.
interface PrintResultType {
code: string;
map?: SourceMap;
toString(): string;
}Convenient command-line interface for running transformations on files directly from the shell or within scripts.
function run(transformer: Transformer, options?: RunOptions): void;
interface Transformer {
(ast: types.ASTNode, callback: (ast: types.ASTNode) => void): void;
}