0
# Code Minification
1
2
Optimize JavaScript code for production deployment with configurable compression, name mangling, and output formatting options based on Terser compatibility.
3
4
## Capabilities
5
6
### Minify Function (Async)
7
8
Minifies JavaScript source code asynchronously with comprehensive optimization options.
9
10
```typescript { .api }
11
/**
12
* Minify JavaScript source code asynchronously
13
* @param src - JavaScript source code string
14
* @param opts - Minification configuration options
15
* @returns Promise resolving to minified code output
16
*/
17
function minify(src: string, opts?: JsMinifyOptions): Promise<Output>;
18
```
19
20
**Usage Examples:**
21
22
```typescript
23
import * as swc from "@swc/wasm";
24
25
// Basic minification
26
const result = await swc.minify(`
27
function calculateTotal(items) {
28
let total = 0;
29
for (const item of items) {
30
total += item.price * item.quantity;
31
}
32
return total;
33
}
34
35
const items = [
36
{ price: 10, quantity: 2 },
37
{ price: 5, quantity: 4 }
38
];
39
40
console.log("Total:", calculateTotal(items));
41
`, {
42
module: false
43
});
44
45
console.log(result.code);
46
// Output: Minified code with shortened variable names
47
48
// Advanced minification with custom options
49
const optimized = await swc.minify(sourceCode, {
50
compress: {
51
dead_code: true,
52
drop_console: true,
53
drop_debugger: true,
54
unused: true
55
},
56
mangle: {
57
toplevel: true,
58
keep_fnames: false
59
},
60
format: {
61
comments: false,
62
semicolons: true
63
},
64
module: true,
65
sourceMap: true
66
});
67
68
// Minify with source maps
69
const withMaps = await swc.minify(code, {
70
sourceMap: true,
71
outputPath: "dist/bundle.js"
72
});
73
74
console.log(withMaps.map); // Source map string
75
```
76
77
### Minify Sync Function
78
79
Minifies JavaScript source code synchronously with identical interface to async version.
80
81
```typescript { .api }
82
/**
83
* Minify JavaScript source code synchronously
84
* @param code - JavaScript source code string
85
* @param opts - Minification configuration options
86
* @returns Minified code output
87
*/
88
function minifySync(code: string, opts?: JsMinifyOptions): Output;
89
```
90
91
**Usage Examples:**
92
93
```typescript
94
import * as swc from "@swc/wasm";
95
96
// Synchronous minification
97
const result = swc.minifySync(`
98
const message = "Hello World";
99
console.log(message);
100
`, {
101
module: false,
102
compress: {
103
unused: true
104
}
105
});
106
107
console.log(result.code);
108
// Output: Compressed code
109
110
// Minify with custom formatting
111
const formatted = swc.minifySync(code, {
112
format: {
113
beautify: true,
114
comments: "some",
115
indentLevel: 2
116
}
117
});
118
```
119
120
## Configuration Options
121
122
### JsMinifyOptions Interface
123
124
```typescript { .api }
125
interface JsMinifyOptions {
126
/** Compression options */
127
compress?: TerserCompressOptions | boolean;
128
/** Output formatting options */
129
format?: JsFormatOptions & ToSnakeCaseProperties<JsFormatOptions>;
130
/** Name mangling options */
131
mangle?: TerserMangleOptions | boolean;
132
/** ECMAScript version target */
133
ecma?: TerserEcmaVersion;
134
/** Keep class names during minification */
135
keep_classnames?: boolean;
136
/** Keep function names during minification */
137
keep_fnames?: boolean;
138
/** Treat input as ES module */
139
module?: boolean;
140
/** Safari 10 compatibility mode */
141
safari10?: boolean;
142
/** Enable top-level minification */
143
toplevel?: boolean;
144
/** Generate source map */
145
sourceMap?: boolean;
146
/** Output path for source map URL */
147
outputPath?: string;
148
/** Inline sources content in source map */
149
inlineSourcesContent?: boolean;
150
}
151
152
type TerserEcmaVersion = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | string | number;
153
```
154
155
### Compression Options
156
157
```typescript { .api }
158
interface TerserCompressOptions {
159
/** Optimize function arguments */
160
arguments?: boolean;
161
/** Optimize arrow functions */
162
arrows?: boolean;
163
/** Optimize boolean expressions */
164
booleans?: boolean;
165
/** Convert booleans to integers */
166
booleans_as_integers?: boolean;
167
/** Collapse single-use variables */
168
collapse_vars?: boolean;
169
/** Optimize comparisons */
170
comparisons?: boolean;
171
/** Optimize computed properties */
172
computed_props?: boolean;
173
/** Optimize conditional expressions */
174
conditionals?: boolean;
175
/** Remove unreachable code */
176
dead_code?: boolean;
177
/** Apply default optimizations */
178
defaults?: boolean;
179
/** Remove directive prologues */
180
directives?: boolean;
181
/** Remove console.* calls */
182
drop_console?: boolean;
183
/** Remove debugger statements */
184
drop_debugger?: boolean;
185
/** ECMAScript version for optimizations */
186
ecma?: TerserEcmaVersion;
187
/** Evaluate constant expressions */
188
evaluate?: boolean;
189
/** Optimize expression sequences */
190
expression?: boolean;
191
/** Global variable definitions */
192
global_defs?: any;
193
/** Hoist function declarations */
194
hoist_funs?: boolean;
195
/** Hoist property accesses */
196
hoist_props?: boolean;
197
/** Hoist variable declarations */
198
hoist_vars?: boolean;
199
/** IE8 compatibility */
200
ie8?: boolean;
201
/** Optimize if-return patterns */
202
if_return?: boolean;
203
/** Function inlining level */
204
inline?: 0 | 1 | 2 | 3;
205
/** Join consecutive variable declarations */
206
join_vars?: boolean;
207
/** Keep class names */
208
keep_classnames?: boolean;
209
/** Keep function arguments */
210
keep_fargs?: boolean;
211
/** Keep function names */
212
keep_fnames?: boolean;
213
/** Keep Infinity literal */
214
keep_infinity?: boolean;
215
/** Optimize loops */
216
loops?: boolean;
217
/** Negate immediately invoked function expressions */
218
negate_iife?: boolean;
219
/** Number of optimization passes */
220
passes?: number;
221
/** Optimize property access */
222
properties?: boolean;
223
/** Assume getter functions are pure */
224
pure_getters?: any;
225
/** List of pure function names */
226
pure_funcs?: string[];
227
/** Reduce function calls */
228
reduce_funcs?: boolean;
229
/** Reduce variable assignments */
230
reduce_vars?: boolean;
231
/** Optimize sequences */
232
sequences?: any;
233
/** Remove code without side effects */
234
side_effects?: boolean;
235
/** Optimize switch statements */
236
switches?: boolean;
237
/** Variables to retain at top level */
238
top_retain?: any;
239
/** Enable top-level optimizations */
240
toplevel?: any;
241
/** Optimize typeof expressions */
242
typeofs?: boolean;
243
/** Enable unsafe optimizations */
244
unsafe?: boolean;
245
/** Unsafe optimization passes */
246
unsafe_passes?: boolean;
247
/** Unsafe arrow function optimizations */
248
unsafe_arrows?: boolean;
249
/** Unsafe comparison optimizations */
250
unsafe_comps?: boolean;
251
/** Unsafe function optimizations */
252
unsafe_function?: boolean;
253
/** Unsafe math optimizations */
254
unsafe_math?: boolean;
255
/** Unsafe symbol optimizations */
256
unsafe_symbols?: boolean;
257
/** Unsafe method optimizations */
258
unsafe_methods?: boolean;
259
/** Unsafe prototype optimizations */
260
unsafe_proto?: boolean;
261
/** Unsafe regex optimizations */
262
unsafe_regexp?: boolean;
263
/** Unsafe undefined optimizations */
264
unsafe_undefined?: boolean;
265
/** Remove unused variables */
266
unused?: boolean;
267
/** Treat as ES module */
268
module?: boolean;
269
}
270
```
271
272
### Name Mangling Options
273
274
```typescript { .api }
275
interface TerserMangleOptions {
276
/** Mangle property names */
277
props?: TerserManglePropertiesOptions;
278
/** Enable top-level mangling */
279
toplevel?: boolean;
280
/** Keep class names */
281
keep_classnames?: boolean;
282
/** Keep function names */
283
keep_fnames?: boolean;
284
/** Keep private property names */
285
keep_private_props?: boolean;
286
/** IE8 compatibility */
287
ie8?: boolean;
288
/** Safari 10 compatibility */
289
safari10?: boolean;
290
/** Reserved names to not mangle */
291
reserved?: string[];
292
}
293
294
interface TerserManglePropertiesOptions {
295
// Property mangling options (implementation-specific)
296
}
297
```
298
299
### Output Formatting Options
300
301
```typescript { .api }
302
interface JsFormatOptions {
303
/** ASCII-only output */
304
asciiOnly?: boolean;
305
/** Beautify output (format code) */
306
beautify?: boolean;
307
/** Force braces around single statements */
308
braces?: boolean;
309
/** Comment preservation strategy */
310
comments?: false | "some" | "all" | { regex: string };
311
/** ECMAScript version for output */
312
ecma?: TerserEcmaVersion;
313
/** Indentation level */
314
indentLevel?: number;
315
/** Starting indentation */
316
indentStart?: number;
317
/** Handle inline scripts */
318
inlineScript?: number;
319
/** Keep numeric precision */
320
keepNumbers?: number;
321
/** Keep quoted property names */
322
keepQuotedProps?: boolean;
323
/** Maximum line length */
324
maxLineLen?: number | false;
325
/** Code preamble */
326
preamble?: string;
327
/** Quote object keys */
328
quoteKeys?: boolean;
329
/** Quote style preference */
330
quoteStyle?: boolean;
331
/** Preserve function annotations */
332
preserveAnnotations?: boolean;
333
/** Safari 10 compatibility */
334
safari10?: boolean;
335
/** Force semicolons */
336
semicolons?: boolean;
337
/** Preserve shebang */
338
shebang?: boolean;
339
/** WebKit compatibility */
340
webkit?: boolean;
341
/** Wrap immediately invoked function expressions */
342
wrapIife?: boolean;
343
/** Wrap function arguments */
344
wrapFuncArgs?: boolean;
345
}
346
```
347
348
## Output Format
349
350
### Output Interface
351
352
```typescript { .api }
353
interface Output {
354
/** Minified code */
355
code: string;
356
/** Source map (if enabled) */
357
map?: string;
358
/** Diagnostic messages */
359
diagnostics: string[];
360
}
361
```
362
363
## Minification Examples
364
365
### Production Optimization
366
367
```typescript
368
const production = await swc.minify(sourceCode, {
369
compress: {
370
// Remove unused code
371
dead_code: true,
372
unused: true,
373
374
// Remove development aids
375
drop_console: true,
376
drop_debugger: true,
377
378
// Aggressive optimizations
379
collapse_vars: true,
380
reduce_vars: true,
381
evaluate: true,
382
383
// Multiple passes for better results
384
passes: 2
385
},
386
mangle: {
387
// Mangle all names including top-level
388
toplevel: true,
389
390
// Keep some function names for debugging
391
keep_fnames: false,
392
keep_classnames: false
393
},
394
format: {
395
// Minimal output
396
comments: false,
397
semicolons: true,
398
beautify: false
399
},
400
ecma: 2018, // Modern browser target
401
module: true
402
});
403
```
404
405
### Development Minification
406
407
```typescript
408
const development = await swc.minify(sourceCode, {
409
compress: {
410
// Basic optimizations only
411
dead_code: true,
412
unused: false, // Keep for debugging
413
414
// Keep development aids
415
drop_console: false,
416
drop_debugger: false
417
},
418
mangle: {
419
// Limited mangling
420
toplevel: false,
421
keep_fnames: true,
422
keep_classnames: true
423
},
424
format: {
425
// Readable output
426
comments: "some",
427
beautify: true,
428
indentLevel: 2
429
},
430
sourceMap: true // Enable source maps
431
});
432
```
433
434
### Library Minification
435
436
```typescript
437
const library = await swc.minify(libraryCode, {
438
compress: {
439
// Conservative optimizations
440
dead_code: true,
441
unused: true,
442
reduce_vars: false, // May break external references
443
444
// Keep globals that may be used externally
445
toplevel: false
446
},
447
mangle: {
448
// Don't mangle top-level names (public API)
449
toplevel: false,
450
keep_fnames: true,
451
452
// Reserve public API names
453
reserved: ["MyLibrary", "publicMethod", "VERSION"]
454
},
455
format: {
456
comments: /^!/, // Keep license comments
457
semicolons: true
458
}
459
});
460
```
461
462
## Error Handling
463
464
Minification functions may fail for:
465
- Syntax errors in input code
466
- Invalid configuration options
467
- Source map generation issues
468
469
```typescript
470
try {
471
const result = await swc.minify(code, options);
472
} catch (error) {
473
console.error("Minification error:", error.message);
474
}
475
476
// Check diagnostics for warnings
477
if (result.diagnostics.length > 0) {
478
console.warn("Minification warnings:", result.diagnostics);
479
}
480
```