JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator
—
Essential functions for parsing source code into ASTs and reprinting modified ASTs back to source code with original formatting preservation.
Parses a string of code into an augmented syntax tree suitable for arbitrary modification and reprinting.
/**
* Parse a string of code into an augmented syntax tree
* @param source - The JavaScript/TypeScript source code to parse
* @param options - Parser and formatting options
* @returns Enhanced AST node with original source tracking
*/
function parse(source: string, options?: Options): types.ASTNode;Usage Examples:
import { parse } from "recast";
// Basic parsing
const ast = parse("function hello() { return 'world'; }");
// Parse with custom parser
const tsAst = parse("const x: number = 42;", {
parser: require("recast/parsers/typescript")
});
// Parse with source map preparation
const ast = parse(sourceCode, {
sourceFileName: "input.js"
});Reprints a modified syntax tree using as much of the original source code as possible.
/**
* Reprint a modified syntax tree preserving original formatting
* @param node - The AST node to print
* @param options - Printing options including source map generation
* @returns PrintResultType with generated code and optional source map
*/
function print(node: types.ASTNode, options?: Options): PrintResultType;Usage Examples:
import { parse, print } from "recast";
const ast = parse(sourceCode);
// ... modify ast ...
const result = print(ast);
console.log(result.code);
// Generate source map
const result = print(ast, {
sourceMapName: "output.js"
});
console.log(result.map); // Source map objectPrints without attempting to reuse any original source code using generic pretty printer.
/**
* Print using generic pretty printer without preserving original formatting
* @param node - The AST node to print
* @param options - Pretty printing options
* @returns PrintResultType with consistently formatted code
*/
function prettyPrint(node: types.ASTNode, options?: Options): PrintResultType;Usage Examples:
import { parse, prettyPrint } from "recast";
const ast = parse(messyCode);
const cleanResult = prettyPrint(ast, {
tabWidth: 2,
quote: "single"
});
console.log(cleanResult.code); // Consistently formatted codeResult object returned by print operations containing the generated code and optional source map.
interface PrintResultType {
/** The generated source code */
code: string;
/** Source map object (if sourceMapName was provided) */
map?: SourceMap;
/** Deprecated method to access code as string */
toString(): string;
}Configuration options shared between parsing and printing operations.
interface Options {
/** Parser to use (default: esprima) */
parser?: any;
/** Number of spaces per tab for indentation (default: 4) */
tabWidth?: number;
/** Use tabs instead of spaces (default: false) */
useTabs?: boolean;
/** Preserve original whitespace when possible (default: true) */
reuseWhitespace?: boolean;
/** Line terminator character(s) (default: OS default) */
lineTerminator?: string;
/** Maximum line length hint (default: 74) */
wrapColumn?: number;
/** Source file name for source map generation */
sourceFileName?: string | null;
/** Source map file name */
sourceMapName?: string | null;
/** Root directory for relative source paths */
sourceRoot?: string | null;
/** Input source map for composition */
inputSourceMap?: string | null;
/** Include .range information (default: false) */
range?: boolean;
/** Don't throw on parse errors (default: true) */
tolerant?: boolean;
/** String quote style: "single", "double", or "auto" */
quote?: "single" | "double" | "auto" | null;
/** Add trailing commas - boolean for all contexts or object for per-context control (default: false) */
trailingComma?: boolean | {
objects?: boolean;
arrays?: boolean;
parameters?: boolean;
};
/** Spaces inside array brackets (default: false) */
arrayBracketSpacing?: boolean;
/** Spaces inside object braces (default: true) */
objectCurlySpacing?: boolean;
/** Always wrap arrow function parameters in parentheses (default: false) */
arrowParensAlways?: boolean;
/** Use commas in Flow object types (default: true) */
flowObjectCommas?: boolean;
/** Include tokens array in AST (default: true) */
tokens?: boolean;
}
/**
* Normalized options with all properties required (no optional fields)
*/
type NormalizedOptions = Required<Omit<Options, "parser" | "esprima">> & {
parser: any;
};
interface SourceMap {
/** Source map version (always 3) */
version: number;
/** Generated file name */
file: string;
/** Root directory for source paths */
sourceRoot?: string;
/** Array of source file names */
sources: string[];
/** Array of source content (optional) */
sourcesContent?: Array<string | null>;
/** Encoded mapping data */
mappings: string;
/** Array of symbol names */
names: string[];
}Install with Tessl CLI
npx tessl i tessl/npm-recast