0
# Core Operations
1
2
Essential functions for parsing source code into ASTs and reprinting modified ASTs back to source code with original formatting preservation.
3
4
## Capabilities
5
6
### Parse Function
7
8
Parses a string of code into an augmented syntax tree suitable for arbitrary modification and reprinting.
9
10
```typescript { .api }
11
/**
12
* Parse a string of code into an augmented syntax tree
13
* @param source - The JavaScript/TypeScript source code to parse
14
* @param options - Parser and formatting options
15
* @returns Enhanced AST node with original source tracking
16
*/
17
function parse(source: string, options?: Options): types.ASTNode;
18
```
19
20
**Usage Examples:**
21
22
```typescript
23
import { parse } from "recast";
24
25
// Basic parsing
26
const ast = parse("function hello() { return 'world'; }");
27
28
// Parse with custom parser
29
const tsAst = parse("const x: number = 42;", {
30
parser: require("recast/parsers/typescript")
31
});
32
33
// Parse with source map preparation
34
const ast = parse(sourceCode, {
35
sourceFileName: "input.js"
36
});
37
```
38
39
### Print Function
40
41
Reprints a modified syntax tree using as much of the original source code as possible.
42
43
```typescript { .api }
44
/**
45
* Reprint a modified syntax tree preserving original formatting
46
* @param node - The AST node to print
47
* @param options - Printing options including source map generation
48
* @returns PrintResultType with generated code and optional source map
49
*/
50
function print(node: types.ASTNode, options?: Options): PrintResultType;
51
```
52
53
**Usage Examples:**
54
55
```typescript
56
import { parse, print } from "recast";
57
58
const ast = parse(sourceCode);
59
// ... modify ast ...
60
const result = print(ast);
61
console.log(result.code);
62
63
// Generate source map
64
const result = print(ast, {
65
sourceMapName: "output.js"
66
});
67
console.log(result.map); // Source map object
68
```
69
70
### Pretty Print Function
71
72
Prints without attempting to reuse any original source code using generic pretty printer.
73
74
```typescript { .api }
75
/**
76
* Print using generic pretty printer without preserving original formatting
77
* @param node - The AST node to print
78
* @param options - Pretty printing options
79
* @returns PrintResultType with consistently formatted code
80
*/
81
function prettyPrint(node: types.ASTNode, options?: Options): PrintResultType;
82
```
83
84
**Usage Examples:**
85
86
```typescript
87
import { parse, prettyPrint } from "recast";
88
89
const ast = parse(messyCode);
90
const cleanResult = prettyPrint(ast, {
91
tabWidth: 2,
92
quote: "single"
93
});
94
console.log(cleanResult.code); // Consistently formatted code
95
```
96
97
### Print Result Type
98
99
Result object returned by print operations containing the generated code and optional source map.
100
101
```typescript { .api }
102
interface PrintResultType {
103
/** The generated source code */
104
code: string;
105
/** Source map object (if sourceMapName was provided) */
106
map?: SourceMap;
107
/** Deprecated method to access code as string */
108
toString(): string;
109
}
110
```
111
112
## Types
113
114
### Options Interface
115
116
Configuration options shared between parsing and printing operations.
117
118
```typescript { .api }
119
interface Options {
120
/** Parser to use (default: esprima) */
121
parser?: any;
122
/** Number of spaces per tab for indentation (default: 4) */
123
tabWidth?: number;
124
/** Use tabs instead of spaces (default: false) */
125
useTabs?: boolean;
126
/** Preserve original whitespace when possible (default: true) */
127
reuseWhitespace?: boolean;
128
/** Line terminator character(s) (default: OS default) */
129
lineTerminator?: string;
130
/** Maximum line length hint (default: 74) */
131
wrapColumn?: number;
132
/** Source file name for source map generation */
133
sourceFileName?: string | null;
134
/** Source map file name */
135
sourceMapName?: string | null;
136
/** Root directory for relative source paths */
137
sourceRoot?: string | null;
138
/** Input source map for composition */
139
inputSourceMap?: string | null;
140
/** Include .range information (default: false) */
141
range?: boolean;
142
/** Don't throw on parse errors (default: true) */
143
tolerant?: boolean;
144
/** String quote style: "single", "double", or "auto" */
145
quote?: "single" | "double" | "auto" | null;
146
/** Add trailing commas - boolean for all contexts or object for per-context control (default: false) */
147
trailingComma?: boolean | {
148
objects?: boolean;
149
arrays?: boolean;
150
parameters?: boolean;
151
};
152
/** Spaces inside array brackets (default: false) */
153
arrayBracketSpacing?: boolean;
154
/** Spaces inside object braces (default: true) */
155
objectCurlySpacing?: boolean;
156
/** Always wrap arrow function parameters in parentheses (default: false) */
157
arrowParensAlways?: boolean;
158
/** Use commas in Flow object types (default: true) */
159
flowObjectCommas?: boolean;
160
/** Include tokens array in AST (default: true) */
161
tokens?: boolean;
162
}
163
164
/**
165
* Normalized options with all properties required (no optional fields)
166
*/
167
type NormalizedOptions = Required<Omit<Options, "parser" | "esprima">> & {
168
parser: any;
169
};
170
171
interface SourceMap {
172
/** Source map version (always 3) */
173
version: number;
174
/** Generated file name */
175
file: string;
176
/** Root directory for source paths */
177
sourceRoot?: string;
178
/** Array of source file names */
179
sources: string[];
180
/** Array of source content (optional) */
181
sourcesContent?: Array<string | null>;
182
/** Encoded mapping data */
183
mappings: string;
184
/** Array of symbol names */
185
names: string[];
186
}
187
```