0
# Code Generation
1
2
Convert Abstract Syntax Trees (AST) back to JavaScript source code with optional source map generation and configurable output formatting.
3
4
## Capabilities
5
6
### Print Function (Async)
7
8
Converts a Program AST back to source code asynchronously with optional configuration.
9
10
```typescript { .api }
11
/**
12
* Convert AST back to source code asynchronously
13
* @param m - Program AST (Module or Script)
14
* @param options - Code generation options
15
* @returns Promise resolving to generated code output
16
*/
17
function print(m: Program, options?: Options): Promise<Output>;
18
```
19
20
**Usage Examples:**
21
22
```typescript
23
import * as swc from "@swc/wasm";
24
25
// Parse then print code
26
const ast = await swc.parse(`
27
class Example {
28
constructor(value) {
29
this.value = value;
30
}
31
}
32
`, {
33
syntax: "ecmascript",
34
target: "es2020"
35
});
36
37
const output = await swc.print(ast, {
38
jsc: {
39
target: "es5"
40
},
41
sourceMaps: true
42
});
43
44
console.log(output.code);
45
// Output: ES5-compatible code
46
47
// Print with specific formatting
48
const formatted = await swc.print(ast, {
49
jsc: {
50
minify: {
51
format: {
52
comments: "some",
53
semicolons: true
54
}
55
}
56
}
57
});
58
59
// Print with source maps
60
const withSourceMap = await swc.print(ast, {
61
sourceMaps: "inline",
62
sourceFileName: "example.js"
63
});
64
65
console.log(withSourceMap.map); // Inline source map
66
```
67
68
### Print Sync Function
69
70
Converts a Program AST back to source code synchronously with identical interface to async version.
71
72
```typescript { .api }
73
/**
74
* Convert AST back to source code synchronously
75
* @param program - Program AST (Module or Script)
76
* @param options - Code generation options
77
* @returns Generated code output
78
*/
79
function printSync(program: Program, options?: Options): Output;
80
```
81
82
**Usage Examples:**
83
84
```typescript
85
import * as swc from "@swc/wasm";
86
87
// Synchronous code generation
88
const ast = swc.parseSync(`const x = 1;`, {
89
syntax: "ecmascript"
90
});
91
92
const output = swc.printSync(ast, {
93
jsc: {
94
target: "es3"
95
}
96
});
97
98
console.log(output.code);
99
100
// Print with minification
101
const minified = swc.printSync(ast, {
102
minify: true,
103
jsc: {
104
minify: {
105
compress: {
106
unused: true
107
},
108
mangle: {
109
toplevel: true
110
}
111
}
112
}
113
});
114
```
115
116
## Configuration Options
117
118
The print functions accept the same `Options` interface as transform functions, allowing comprehensive control over code generation.
119
120
### Key Generation Options
121
122
```typescript { .api }
123
interface Options extends Config {
124
/** Source filename for source maps */
125
sourceFileName?: string;
126
/** Source root for source maps */
127
sourceRoot?: string;
128
/** Output path for source map fixing */
129
outputPath?: string;
130
/** Working directory for path resolution */
131
cwd?: string;
132
}
133
134
interface Config {
135
/** JavaScript compiler configuration */
136
jsc?: JscConfig;
137
/** Module format configuration */
138
module?: ModuleConfig;
139
/** Enable minification during generation */
140
minify?: boolean;
141
/** Source map generation */
142
sourceMaps?: boolean | "inline";
143
/** Include source content in source maps */
144
inlineSourcesContent?: boolean;
145
}
146
```
147
148
### Output Formatting
149
150
Control code generation formatting through JscConfig:
151
152
```typescript { .api }
153
interface JscConfig {
154
/** Compilation target affecting syntax */
155
target?: JscTarget;
156
/** Minification options for formatting */
157
minify?: JsMinifyOptions;
158
/** Preserve all comments */
159
preserveAllComments?: boolean;
160
/** Output character encoding */
161
output?: {
162
charset?: "utf8" | "ascii";
163
};
164
}
165
166
interface JsMinifyOptions {
167
/** Output formatting options */
168
format?: JsFormatOptions;
169
/** Compression settings */
170
compress?: boolean | TerserCompressOptions;
171
/** Name mangling settings */
172
mangle?: boolean | TerserMangleOptions;
173
}
174
175
interface JsFormatOptions {
176
/** Comment preservation strategy */
177
comments?: false | "some" | "all" | { regex: string };
178
/** Semicolon insertion */
179
semicolons?: boolean;
180
/** ASCII-only output */
181
asciiOnly?: boolean;
182
/** Beautify output */
183
beautify?: boolean;
184
/** Maximum line length */
185
maxLineLen?: number | false;
186
/** Indentation level */
187
indentLevel?: number;
188
}
189
```
190
191
## Output Format
192
193
### Output Interface
194
195
```typescript { .api }
196
interface Output {
197
/** Generated source code */
198
code: string;
199
/** Source map (if enabled) */
200
map?: string;
201
/** Diagnostic messages */
202
diagnostics: string[];
203
}
204
```
205
206
The `diagnostics` array typically contains warnings about code generation, such as:
207
- Unsupported syntax for target version
208
- Source map generation issues
209
- Comment preservation conflicts
210
211
## Source Map Generation
212
213
### Basic Source Maps
214
215
```typescript
216
const ast = await swc.parse(sourceCode, { syntax: "typescript" });
217
218
const output = await swc.print(ast, {
219
sourceMaps: true,
220
sourceFileName: "input.ts",
221
sourceRoot: "/src"
222
});
223
224
// output.map contains the source map string
225
```
226
227
### Inline Source Maps
228
229
```typescript
230
const output = await swc.print(ast, {
231
sourceMaps: "inline",
232
inlineSourcesContent: true
233
});
234
235
// Source map is embedded in output.code as data URL
236
```
237
238
## Target-Specific Generation
239
240
### ES5 Output
241
242
```typescript
243
const es5Output = await swc.print(ast, {
244
jsc: {
245
target: "es5"
246
}
247
});
248
// Transforms classes, arrow functions, etc. to ES5
249
```
250
251
### Module Format Conversion
252
253
```typescript
254
// Convert to CommonJS
255
const cjsOutput = await swc.print(ast, {
256
module: {
257
type: "commonjs"
258
}
259
});
260
261
// Convert to UMD
262
const umdOutput = await swc.print(ast, {
263
module: {
264
type: "umd",
265
globals: {
266
"react": "React",
267
"lodash": "_"
268
}
269
}
270
});
271
```
272
273
## Advanced Generation Patterns
274
275
### Formatted Code Generation
276
277
```typescript
278
const formatted = await swc.print(ast, {
279
jsc: {
280
minify: {
281
format: {
282
comments: "all",
283
beautify: true,
284
indentLevel: 2,
285
semicolons: true,
286
maxLineLen: 80
287
}
288
}
289
}
290
});
291
```
292
293
### Optimized Production Output
294
295
```typescript
296
const optimized = await swc.print(ast, {
297
minify: true,
298
jsc: {
299
target: "es2018",
300
minify: {
301
compress: {
302
dead_code: true,
303
drop_console: true,
304
unused: true
305
},
306
mangle: {
307
toplevel: true
308
},
309
format: {
310
comments: false
311
}
312
}
313
}
314
});
315
```
316
317
## Error Handling
318
319
Print functions may throw errors for:
320
- Invalid AST structure
321
- Unsupported node types for target
322
- Source map generation failures
323
324
```typescript
325
try {
326
const output = await swc.print(ast, options);
327
} catch (error) {
328
console.error("Code generation error:", error.message);
329
}
330
```
331
332
Diagnostic warnings are included in the `diagnostics` array rather than throwing exceptions.