0
# Code Transformation
1
2
Transform JavaScript and TypeScript code with configurable compilation targets, module systems, and optimization settings. Supports both string input and AST Program objects.
3
4
## Capabilities
5
6
### Transform Function (Async)
7
8
Transforms source code or AST asynchronously with comprehensive configuration options.
9
10
```typescript { .api }
11
/**
12
* Transform source code or AST asynchronously
13
* @param code - Source code string or Program AST
14
* @param options - Transformation configuration options
15
* @param experimental_plugin_bytes_resolver - Plugin bytes resolver (experimental)
16
* @returns Promise resolving to transformation output
17
*/
18
function transform(
19
code: string | Program,
20
options?: Options,
21
experimental_plugin_bytes_resolver?: any
22
): Promise<Output>;
23
```
24
25
**Usage Examples:**
26
27
```typescript
28
import * as swc from "@swc/wasm";
29
30
// Transform TypeScript to JavaScript
31
const result = await swc.transform(`
32
interface Config {
33
port: number;
34
host: string;
35
}
36
37
const config: Config = {
38
port: 3000,
39
host: "localhost"
40
};
41
42
export default config;
43
`, {
44
jsc: {
45
target: "es2018",
46
parser: {
47
syntax: "typescript"
48
}
49
},
50
module: {
51
type: "commonjs"
52
}
53
});
54
55
console.log(result.code);
56
// Output: CommonJS JavaScript code
57
58
// Transform with React JSX
59
const jsxResult = await swc.transform(`
60
function App() {
61
return <div>Hello World</div>;
62
}
63
`, {
64
jsc: {
65
target: "es2015",
66
parser: {
67
syntax: "ecmascript",
68
jsx: true
69
},
70
transform: {
71
react: {
72
pragma: "React.createElement",
73
pragmaFrag: "React.Fragment"
74
}
75
}
76
}
77
});
78
79
// Transform with source maps
80
const mappedResult = await swc.transform(sourceCode, {
81
sourceMaps: true,
82
filename: "input.ts",
83
jsc: {
84
target: "es2020",
85
parser: {
86
syntax: "typescript"
87
}
88
}
89
});
90
91
console.log(mappedResult.map); // Source map string
92
```
93
94
### Transform Sync Function
95
96
Transforms source code or AST synchronously with identical interface to async version.
97
98
```typescript { .api }
99
/**
100
* Transform source code or AST synchronously
101
* @param code - Source code string or Program AST
102
* @param opts - Transformation configuration options
103
* @param experimental_plugin_bytes_resolver - Plugin bytes resolver (experimental)
104
* @returns Transformation output
105
*/
106
function transformSync(
107
code: string | Program,
108
opts?: Options,
109
experimental_plugin_bytes_resolver?: any
110
): Output;
111
```
112
113
**Usage Examples:**
114
115
```typescript
116
import * as swc from "@swc/wasm";
117
118
// Synchronous transformation
119
const result = swc.transformSync(`class Example {}`, {
120
jsc: {
121
target: "es5",
122
parser: {
123
syntax: "ecmascript"
124
}
125
}
126
});
127
128
// Transform AST object
129
const ast = swc.parseSync(`const x = 1;`, {
130
syntax: "ecmascript"
131
});
132
133
const transformed = swc.transformSync(ast, {
134
jsc: {
135
target: "es3"
136
}
137
});
138
```
139
140
## Configuration Options
141
142
### Main Options Interface
143
144
```typescript { .api }
145
interface Options extends Config {
146
/** Parse as script instead of module */
147
script?: boolean;
148
/** Working directory for path resolution */
149
cwd?: string;
150
/** Caller identification options */
151
caller?: CallerOptions;
152
/** Filename for error reporting and config resolution */
153
filename?: string;
154
/** Root directory for config resolution */
155
root?: string;
156
/** Root resolution mode */
157
rootMode?: "root" | "upward" | "upward-optional";
158
/** Environment name for config selection */
159
envName?: string;
160
/** Config file path or disable */
161
configFile?: string | boolean;
162
/** Enable .swcrc file loading */
163
swcrc?: boolean;
164
/** Root packages for .swcrc resolution */
165
swcrcRoots?: boolean | MatchPattern | MatchPattern[];
166
/** Input source map */
167
inputSourceMap?: boolean | string;
168
/** Source filename in source maps */
169
sourceFileName?: string;
170
/** Source root in source maps */
171
sourceRoot?: string;
172
/** Plugin configuration */
173
plugin?: Plugin;
174
/** Module type detection */
175
isModule?: boolean | "unknown" | "commonjs";
176
/** Output path for source map fixing */
177
outputPath?: string;
178
}
179
180
interface CallerOptions {
181
name: string;
182
[key: string]: any;
183
}
184
```
185
186
### Core Configuration
187
188
```typescript { .api }
189
interface Config {
190
/** File matching patterns */
191
test?: string | string[];
192
/** File exclusion patterns */
193
exclude?: string | string[];
194
/** Environment-based configuration */
195
env?: EnvConfig;
196
/** JavaScript compiler configuration */
197
jsc?: JscConfig;
198
/** Module transformation configuration */
199
module?: ModuleConfig;
200
/** Enable minification */
201
minify?: boolean;
202
/** Source map generation */
203
sourceMaps?: boolean | "inline";
204
/** Include source content in source maps */
205
inlineSourcesContent?: boolean;
206
}
207
```
208
209
### JavaScript Compiler Configuration
210
211
```typescript { .api }
212
interface JscConfig {
213
/** Use loose transformations */
214
loose?: boolean;
215
/** Parser configuration */
216
parser?: ParserConfig;
217
/** Transformation settings */
218
transform?: TransformConfig;
219
/** Use external helpers from @swc/helpers */
220
externalHelpers?: boolean;
221
/** Compilation target */
222
target?: JscTarget;
223
/** Keep class names during minification */
224
keepClassNames?: boolean;
225
/** Experimental features */
226
experimental?: {
227
optimizeHygiene?: boolean;
228
keepImportAssertions?: boolean;
229
cacheRoot?: string;
230
plugins?: Array<[string, Record<string, any>]>;
231
};
232
/** Base URL for path resolution */
233
baseUrl?: string;
234
/** Path mapping */
235
paths?: { [from: string]: string[] };
236
/** Minification options */
237
minify?: JsMinifyOptions;
238
/** Preserve all comments */
239
preserveAllComments?: boolean;
240
/** Output settings */
241
output?: {
242
charset?: "utf8" | "ascii";
243
};
244
}
245
246
type JscTarget = "es3" | "es5" | "es2015" | "es2016" | "es2017" | "es2018" | "es2019" | "es2020" | "es2021" | "es2022";
247
```
248
249
### Transform Configuration
250
251
```typescript { .api }
252
interface TransformConfig {
253
/** React transformation settings */
254
react?: ReactConfig;
255
/** Constant modules configuration */
256
constModules?: ConstModulesConfig;
257
/** Optimizer configuration */
258
optimizer?: OptimizerConfig;
259
/** Legacy decorator support */
260
legacyDecorator?: boolean;
261
/** Decorator metadata support */
262
decoratorMetadata?: boolean;
263
/** Treat const enum as enum */
264
treatConstEnumAsEnum?: boolean;
265
/** Use define for class fields */
266
useDefineForClassFields?: boolean;
267
}
268
269
interface ReactConfig {
270
/** JSX pragma function */
271
pragma?: string;
272
/** JSX Fragment component */
273
pragmaFrag?: string;
274
/** Throw on XML namespaced tags */
275
throwIfNamespace?: boolean;
276
/** Development mode helpers */
277
development?: boolean;
278
/** Use Object.assign instead of _extends */
279
useBuiltins?: boolean;
280
/** Fast refresh configuration */
281
refresh?: boolean | {
282
refreshReg?: string;
283
refreshSig?: string;
284
emitFullSignatures?: boolean;
285
};
286
/** JSX runtime mode */
287
runtime?: "automatic" | "classic";
288
/** JSX import source */
289
importSource?: string;
290
}
291
```
292
293
### Module Configuration
294
295
```typescript { .api }
296
type ModuleConfig = Es6Config | CommonJsConfig | UmdConfig | AmdConfig | NodeNextConfig | SystemjsConfig;
297
298
interface BaseModuleConfig {
299
/** Strict mode for __esModule */
300
strict?: boolean;
301
/** Emit 'use strict' directive */
302
strictMode?: boolean;
303
/** Lazy import initialization */
304
lazy?: boolean | string[];
305
/** Import interop strategy */
306
importInterop?: "swc" | "babel" | "node" | "none";
307
/** Output file extension */
308
outFileExtension?: "js" | "mjs" | "cjs";
309
/** Export interop annotation */
310
exportInteropAnnotation?: boolean;
311
/** Preserve dynamic imports */
312
ignoreDynamic?: boolean;
313
/** Allow top-level this */
314
allowTopLevelThis?: boolean;
315
/** Preserve import.meta */
316
preserveImportMeta?: boolean;
317
/** Resolve fully */
318
resolveFully?: boolean;
319
}
320
321
interface Es6Config extends BaseModuleConfig {
322
type: "es6";
323
}
324
325
interface CommonJsConfig extends BaseModuleConfig {
326
type: "commonjs";
327
}
328
329
interface UmdConfig extends BaseModuleConfig {
330
type: "umd";
331
globals?: { [key: string]: string };
332
}
333
334
interface AmdConfig extends BaseModuleConfig {
335
type: "amd";
336
moduleId?: string;
337
}
338
339
interface NodeNextConfig extends BaseModuleConfig {
340
type: "nodenext";
341
}
342
343
interface SystemjsConfig {
344
type: "systemjs";
345
allowTopLevelThis?: boolean;
346
}
347
```
348
349
## Output Format
350
351
### Output Interface
352
353
```typescript { .api }
354
interface Output {
355
/** Transformed code */
356
code: string;
357
/** Source map (if enabled) */
358
map?: string;
359
/** Diagnostic messages */
360
diagnostics: string[];
361
}
362
```
363
364
**Usage Example:**
365
366
```typescript
367
const result = await swc.transform(code, options);
368
369
console.log(result.code); // Transformed JavaScript
370
console.log(result.map); // Source map (if sourceMaps: true)
371
console.log(result.diagnostics); // Array of warning/error messages
372
```
373
374
## Advanced Transformation Patterns
375
376
### Path Mapping
377
378
```typescript
379
const result = await swc.transform(`
380
import { utils } from '@app/utils';
381
import { config } from '@shared/config';
382
`, {
383
filename: "src/main.ts",
384
jsc: {
385
parser: { syntax: "typescript" },
386
target: "es2018",
387
baseUrl: "./",
388
paths: {
389
"@app/*": ["src/*"],
390
"@shared/*": ["shared/*"]
391
}
392
},
393
module: { type: "commonjs" }
394
});
395
```
396
397
### Environment-Based Configuration
398
399
```typescript
400
const result = await swc.transform(code, {
401
env: {
402
targets: {
403
"chrome": "58",
404
"ie": "11"
405
},
406
mode: "usage",
407
coreJs: "3.21"
408
},
409
jsc: {
410
parser: { syntax: "typescript" },
411
target: "es5"
412
}
413
});
414
```