0
# Advanced Features
1
2
Advanced functionality including AST manipulation, custom identifier mangling, default option introspection, and SpiderMonkey AST support for specialized use cases and deep integrations.
3
4
## Capabilities
5
6
### Default Options Introspection
7
8
Retrieve complete default configuration for all Terser components, useful for option discovery and configuration validation.
9
10
```typescript { .api }
11
/**
12
* Get default options for all Terser components
13
* @returns Promise resolving to object containing default options for each component
14
*/
15
async function _default_options(): Promise<object>;
16
```
17
18
**Usage Examples:**
19
20
```typescript
21
import { _default_options } from "terser";
22
23
// Discover available options
24
const defaults = await _default_options();
25
console.log(defaults);
26
// Output includes: compress, mangle, format, parse, etc.
27
28
// Use as base for custom configuration
29
const customOptions = {
30
...defaults.compress,
31
drop_console: true,
32
passes: 3
33
};
34
```
35
36
### Custom Identifier Mangling
37
38
Advanced name mangling system supporting custom identifier generation algorithms and character frequency analysis.
39
40
```typescript { .api }
41
/**
42
* Simple identifier mangler interface for deterministic name generation
43
*/
44
interface SimpleIdentifierMangler {
45
/**
46
* Generate the nth most preferred identifier name
47
* @param n - Ordinal identifier index (0-based)
48
* @returns Generated identifier name
49
*/
50
get(n: number): string;
51
}
52
53
/**
54
* Advanced identifier mangler with character frequency optimization
55
*/
56
interface WeightedIdentifierMangler extends SimpleIdentifierMangler {
57
/**
58
* Adjust character frequency weights based on input analysis
59
* @param chars - Characters to analyze
60
* @param delta - Weight adjustment value
61
* @returns Updated weight value
62
*/
63
consider(chars: string, delta: number): number;
64
65
/**
66
* Reset all character frequency weights to initial state
67
*/
68
reset(): void;
69
70
/**
71
* Sort identifiers by frequency for optimal compression
72
*/
73
sort(): void;
74
}
75
```
76
77
**Usage Examples:**
78
79
```typescript
80
// Simple custom mangler
81
class CustomMangler implements SimpleIdentifierMangler {
82
get(n: number): string {
83
// Generate custom identifier names
84
return `_${n.toString(36)}`;
85
}
86
}
87
88
// Use with mangle options
89
await minify(code, {
90
mangle: {
91
nth_identifier: new CustomMangler()
92
}
93
});
94
95
// Weighted mangler for frequency optimization
96
class FrequencyMangler implements WeightedIdentifierMangler {
97
private weights = new Map<string, number>();
98
99
get(n: number): string {
100
// Implementation based on character frequency
101
return this.generateFromWeights(n);
102
}
103
104
consider(chars: string, delta: number): number {
105
// Adjust weights based on character usage
106
for (const char of chars) {
107
const current = this.weights.get(char) || 0;
108
this.weights.set(char, current + delta);
109
}
110
return delta;
111
}
112
113
reset(): void {
114
this.weights.clear();
115
}
116
117
sort(): void {
118
// Sort by frequency for optimal identifier generation
119
}
120
}
121
```
122
123
### Property Mangling Options
124
125
Advanced property name mangling with regex filtering, builtin handling, and debugging support.
126
127
```typescript { .api }
128
interface ManglePropertiesOptions {
129
/** Mangle properties that overlap with built-in names */
130
builtins?: boolean;
131
/** Add debug prefix/suffix to mangled properties */
132
debug?: boolean;
133
/** Quote handling for property names */
134
keep_quoted?: boolean | 'strict';
135
/** Custom identifier generation for properties */
136
nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler;
137
/** Only mangle properties matching regex pattern */
138
regex?: RegExp | string;
139
/** Property names to exclude from mangling */
140
reserved?: string[];
141
}
142
```
143
144
**Usage Examples:**
145
146
```typescript
147
await minify(code, {
148
mangle: {
149
properties: {
150
// Only mangle private-style properties
151
regex: /^_/,
152
reserved: ['_config', '_internal'],
153
debug: true // Add debug markers
154
}
155
}
156
});
157
158
// Strict quoted property handling
159
await minify(code, {
160
mangle: {
161
properties: {
162
keep_quoted: 'strict', // Never mangle quoted properties
163
builtins: false // Preserve builtin property names
164
}
165
}
166
});
167
```
168
169
### Source Map Integration
170
171
Advanced source map configuration for complex build scenarios and debugging workflows.
172
173
```typescript { .api }
174
interface SourceMapOptions {
175
/** Input source map content */
176
content?: SectionedSourceMapInput | string;
177
/** Include original source content in map */
178
includeSources?: boolean;
179
/** Output filename for source map */
180
filename?: string;
181
/** Source root path */
182
root?: string;
183
/** Return source map as object instead of JSON string */
184
asObject?: boolean;
185
/** Source map URL or 'inline' for data URI */
186
url?: string | 'inline';
187
}
188
```
189
190
**Usage Examples:**
191
192
```typescript
193
// Chain source maps through build pipeline
194
const previousMap = JSON.parse(fs.readFileSync('input.js.map', 'utf8'));
195
196
const result = await minify(code, {
197
sourceMap: {
198
content: previousMap, // Chain from previous step
199
filename: 'output.js.map',
200
includeSources: true, // Embed original sources
201
root: '/src' // Source root for debugging
202
}
203
});
204
205
// Inline source map for development
206
const devResult = await minify(code, {
207
sourceMap: {
208
url: 'inline', // Embed as data URI
209
includeSources: true
210
}
211
});
212
```
213
214
### AST Processing and Mozilla Support
215
216
Support for SpiderMonkey AST format and direct AST manipulation for advanced use cases.
217
218
```typescript { .api }
219
// AST input/output support through parse options
220
interface ParseOptions {
221
/** Parse input as SpiderMonkey AST format */
222
spidermonkey?: boolean;
223
}
224
225
interface FormatOptions {
226
/** Output SpiderMonkey AST instead of code */
227
spidermonkey?: boolean;
228
/** Include AST in output object */
229
ast?: boolean;
230
}
231
```
232
233
**Usage Examples:**
234
235
```typescript
236
// Process SpiderMonkey AST
237
const spidermonkeyAST = { /* SpiderMonkey AST object */ };
238
239
const result = await minify(spidermonkeyAST, {
240
parse: { spidermonkey: true },
241
format: { spidermonkey: true }
242
});
243
// result.ast contains processed SpiderMonkey AST
244
245
// Preserve AST for further processing
246
const withAST = await minify(code, {
247
format: { ast: true }
248
});
249
// withAST.ast contains Terser AST object
250
```
251
252
### Name Cache Management
253
254
Persistent caching system for consistent identifier mangling across multiple builds.
255
256
```typescript { .api }
257
interface NameCacheObject {
258
/** Variable name mappings */
259
vars?: { [originalName: string]: string };
260
/** Property name mappings */
261
props?: { [originalName: string]: string };
262
}
263
```
264
265
**Usage Examples:**
266
267
```typescript
268
// Load existing name cache
269
const nameCache = JSON.parse(fs.readFileSync('names.json', 'utf8'));
270
271
const result = await minify(code, {
272
nameCache,
273
mangle: {
274
cache: nameCache.vars || {}
275
}
276
});
277
278
// Save updated cache for next build
279
fs.writeFileSync('names.json', JSON.stringify(result.nameCache));
280
281
// Separate caches for different build targets
282
const prodCache = { vars: {}, props: {} };
283
const devCache = { vars: {}, props: {} };
284
```
285
286
### Error and Debug Information
287
288
Advanced error handling and debugging capabilities for development and troubleshooting.
289
290
```typescript
291
// Enable debug logging via environment variable
292
process.env.TERSER_DEBUG_DIR = './debug';
293
294
try {
295
const result = await minify(code, {
296
timings: true // Include timing information
297
});
298
299
console.log('Processing times:', result.timings);
300
// Output: { parse: 0.123, compress: 0.456, mangle: 0.078, ... }
301
302
} catch (error) {
303
// Detailed error information
304
console.error('Line:', error.line);
305
console.error('Column:', error.col);
306
console.error('Context:', error.filename);
307
}
308
```
309
310
### Utility Functions
311
312
Base64 decoding utility for working with inline source maps and encoded content.
313
314
```typescript { .api }
315
/**
316
* Decode base64-encoded strings to ASCII
317
* @param base64 - Base64-encoded string
318
* @returns Decoded ASCII string
319
*/
320
function to_ascii(base64: string): string;
321
```
322
323
**Usage Examples:**
324
325
```typescript
326
import { to_ascii } from "terser";
327
328
// Decode inline source map
329
const inlineMap = "eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9";
330
const decoded = to_ascii(inlineMap);
331
console.log(JSON.parse(decoded)); // Source map object
332
```
333
334
## Performance Optimization
335
336
Advanced techniques for optimizing Terser performance in production environments:
337
338
### Compression Passes
339
340
```typescript
341
// Multiple compression passes for maximum optimization
342
const result = await minify(code, {
343
compress: {
344
passes: 3, // Multiple optimization passes
345
pure_funcs: [ // Mark functions as pure for removal
346
'console.log',
347
'debug.log'
348
]
349
}
350
});
351
```
352
353
### Parallel Processing
354
355
```typescript
356
// Process multiple files in parallel
357
const files = ['file1.js', 'file2.js', 'file3.js'];
358
const results = await Promise.all(
359
files.map(file =>
360
minify(fs.readFileSync(file, 'utf8'), options)
361
)
362
);
363
```
364
365
### Memory Management
366
367
```typescript
368
// Minimize memory usage for large codebases
369
const result = await minify(code, {
370
format: {
371
ast: false, // Don't preserve AST
372
comments: false // Remove comments
373
}
374
});
375
```