0
# Name Mangling
1
2
Advanced name obfuscation system providing variable, function, and property name shortening with customizable preservation rules and identifier generation algorithms for maximum code size reduction.
3
4
## Capabilities
5
6
### Mangle Options
7
8
Core name mangling configuration controlling variable, function, and property name transformation.
9
10
```typescript { .api }
11
interface MangleOptions {
12
/** Mangle names in eval scope (risky) */
13
eval?: boolean;
14
/** Preserve class names during mangling */
15
keep_classnames?: boolean | RegExp;
16
/** Preserve function names during mangling */
17
keep_fnames?: boolean | RegExp;
18
/** Treat code as ES6 module */
19
module?: boolean;
20
/** Custom identifier generation algorithm */
21
nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler;
22
/** Enable/configure property name mangling */
23
properties?: boolean | ManglePropertiesOptions;
24
/** Names to exclude from mangling */
25
reserved?: string[];
26
/** Safari 10 compatibility mode */
27
safari10?: boolean;
28
/** Apply mangling to top-level scope */
29
toplevel?: boolean;
30
}
31
```
32
33
### Basic Variable Mangling
34
35
Standard variable and function name shortening for local scopes.
36
37
**Usage Examples:**
38
39
```typescript
40
// Basic mangling
41
const result = await minify(code, {
42
mangle: true // Enable with default settings
43
});
44
45
// Custom mangling options
46
const result = await minify(code, {
47
mangle: {
48
reserved: ['$', 'jQuery', 'angular'], // Don't mangle these names
49
keep_fnames: true, // Preserve function names
50
keep_classnames: /^Component/ // Preserve class names matching regex
51
}
52
});
53
54
// Before: function calculateTotalPrice(items) { var sum = 0; return sum; }
55
// After: function calculateTotalPrice(e) { var a = 0; return a; }
56
```
57
58
### Top-level Mangling
59
60
Mangle names in global/top-level scope for maximum compression.
61
62
**Usage Examples:**
63
64
```typescript
65
// Enable top-level mangling
66
const result = await minify(code, {
67
mangle: {
68
toplevel: true // Mangle global variables and functions
69
}
70
});
71
72
// Module-aware mangling
73
const result = await minify(code, {
74
mangle: {
75
module: true, // ES6 module mode
76
toplevel: true // Safe for modules
77
}
78
});
79
80
// Before: var globalConfig = {}; function initApp() {}
81
// After: var a = {}; function b() {}
82
```
83
84
### Property Mangling
85
86
Advanced property name obfuscation with regex filtering and preservation rules.
87
88
```typescript { .api }
89
interface ManglePropertiesOptions {
90
/** Mangle properties that overlap with built-in JavaScript names */
91
builtins?: boolean;
92
/** Add debug prefix/suffix to mangled property names */
93
debug?: boolean;
94
/** Handle quoted property names */
95
keep_quoted?: boolean | 'strict';
96
/** Custom identifier generation for properties */
97
nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler;
98
/** Only mangle properties matching this pattern */
99
regex?: RegExp | string;
100
/** Property names to exclude from mangling */
101
reserved?: string[];
102
}
103
```
104
105
**Usage Examples:**
106
107
```typescript
108
// Basic property mangling
109
const result = await minify(code, {
110
mangle: {
111
properties: true // Mangle all properties
112
}
113
});
114
115
// Selective property mangling
116
const result = await minify(code, {
117
mangle: {
118
properties: {
119
regex: /^_/, // Only mangle private-style properties
120
reserved: ['_config'], // But preserve _config
121
keep_quoted: true // Don't mangle quoted properties
122
}
123
}
124
});
125
126
// Advanced property mangling
127
const result = await minify(code, {
128
mangle: {
129
properties: {
130
regex: /^(get|set)_/, // Mangle getters/setters
131
debug: true, // Add debug info
132
builtins: false // Don't mangle built-in names
133
}
134
}
135
});
136
137
// Before: obj._privateMethod(); obj["public_api"]();
138
// After: obj.a(); obj["public_api"](); // quoted preserved
139
```
140
141
### Name Reservation
142
143
Comprehensive name preservation system for external APIs and required identifiers.
144
145
**Usage Examples:**
146
147
```typescript
148
// Framework integration
149
const result = await minify(code, {
150
mangle: {
151
reserved: [
152
// jQuery
153
'$', 'jQuery',
154
// Angular
155
'angular', 'module', 'controller',
156
// React
157
'React', 'Component', 'render',
158
// Custom API
159
'MyLibrary', 'PUBLIC_API'
160
]
161
}
162
});
163
164
// RegExp-based preservation
165
const result = await minify(code, {
166
mangle: {
167
keep_fnames: /^(init|destroy|render)$/, // Preserve lifecycle methods
168
keep_classnames: /Component$/, // Preserve component classes
169
reserved: ['CONSTANTS', 'CONFIG'] // Preserve specific names
170
}
171
});
172
```
173
174
### Custom Identifier Generation
175
176
Advanced identifier generation with pluggable algorithms and frequency optimization.
177
178
```typescript { .api }
179
/**
180
* Simple identifier mangler interface
181
*/
182
interface SimpleIdentifierMangler {
183
/**
184
* Generate identifier for given ordinal
185
* @param n - Zero-based identifier index
186
* @returns Generated identifier string
187
*/
188
get(n: number): string;
189
}
190
191
/**
192
* Weighted identifier mangler with frequency analysis
193
*/
194
interface WeightedIdentifierMangler extends SimpleIdentifierMangler {
195
/**
196
* Update character frequency weights
197
* @param chars - Characters to analyze
198
* @param delta - Weight adjustment
199
* @returns Updated weight
200
*/
201
consider(chars: string, delta: number): number;
202
203
/** Reset frequency analysis */
204
reset(): void;
205
206
/** Sort identifiers by frequency */
207
sort(): void;
208
}
209
```
210
211
**Usage Examples:**
212
213
```typescript
214
// Custom simple mangler
215
class PrefixMangler implements SimpleIdentifierMangler {
216
get(n: number): string {
217
return `_${n.toString(36)}`; // _0, _1, _2, ...
218
}
219
}
220
221
// Frequency-based mangler
222
class FrequencyMangler implements WeightedIdentifierMangler {
223
private weights = new Map<string, number>();
224
225
get(n: number): string {
226
// Generate based on character frequency
227
return this.generateOptimal(n);
228
}
229
230
consider(chars: string, delta: number): number {
231
// Track character usage patterns
232
for (const char of chars) {
233
const current = this.weights.get(char) || 0;
234
this.weights.set(char, current + delta);
235
}
236
return delta;
237
}
238
239
reset(): void {
240
this.weights.clear();
241
}
242
243
sort(): void {
244
// Optimize identifier order by frequency
245
}
246
}
247
248
// Use custom mangler
249
const result = await minify(code, {
250
mangle: {
251
nth_identifier: new PrefixMangler()
252
}
253
});
254
```
255
256
### Name Cache Persistence
257
258
Consistent name mapping across multiple builds and incremental compilation.
259
260
**Usage Examples:**
261
262
```typescript
263
// Load previous name cache
264
const nameCache = JSON.parse(fs.readFileSync('names.json', 'utf8'));
265
266
const result = await minify(code, {
267
nameCache, // Use existing mappings
268
mangle: true
269
});
270
271
// Save updated cache
272
fs.writeFileSync('names.json', JSON.stringify(result.nameCache));
273
274
// Separate caches for different targets
275
const libCache = { vars: {}, props: {} };
276
const appCache = { vars: {}, props: {} };
277
278
// Library build
279
const libResult = await minify(libCode, {
280
nameCache: libCache,
281
mangle: { toplevel: false } // Don't mangle exports
282
});
283
284
// Application build
285
const appResult = await minify(appCode, {
286
nameCache: appCache,
287
mangle: { toplevel: true } // Mangle everything
288
});
289
```
290
291
### Safari and IE Compatibility
292
293
Special handling for browser compatibility issues with name mangling.
294
295
**Usage Examples:**
296
297
```typescript
298
// Safari 10 compatibility
299
const result = await minify(code, {
300
mangle: {
301
safari10: true // Avoid Safari 10 mangling bugs
302
}
303
});
304
305
// IE8 compatibility
306
const result = await minify(code, {
307
mangle: {
308
reserved: ['default'] // IE8 keyword issues
309
},
310
compress: {
311
ie8: true
312
}
313
});
314
```
315
316
### Eval Scope Mangling
317
318
Risky but powerful mangling for code using eval and dynamic execution.
319
320
**Usage Examples:**
321
322
```typescript
323
// Conservative approach (default)
324
const result = await minify(code, {
325
mangle: {
326
eval: false // Don't mangle in eval scope (safe)
327
}
328
});
329
330
// Aggressive approach (risky)
331
const result = await minify(code, {
332
mangle: {
333
eval: true // Mangle even in eval scope (may break code)
334
}
335
});
336
```
337
338
## Types
339
340
```typescript { .api }
341
interface MangleOptions {
342
eval?: boolean;
343
keep_classnames?: boolean | RegExp;
344
keep_fnames?: boolean | RegExp;
345
module?: boolean;
346
nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler;
347
properties?: boolean | ManglePropertiesOptions;
348
reserved?: string[];
349
safari10?: boolean;
350
toplevel?: boolean;
351
}
352
353
interface ManglePropertiesOptions {
354
builtins?: boolean;
355
debug?: boolean;
356
keep_quoted?: boolean | 'strict';
357
nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler;
358
regex?: RegExp | string;
359
reserved?: string[];
360
}
361
```