0
# Advanced Features
1
2
Performance optimization and customization capabilities for large-scale webpack builds.
3
4
## Capabilities
5
6
### Caching System
7
8
File-based caching for faster incremental builds and CI/CD pipeline optimization.
9
10
```javascript { .api }
11
/**
12
* Enable file caching for faster rebuilds
13
* @type {boolean | string}
14
* @default false
15
*/
16
cache: boolean | string;
17
18
/**
19
* Override default cache keys for fine-grained cache invalidation control
20
* @param {object} defaultCacheKeys - Default cache key object
21
* @param {string} file - File path being processed
22
* @returns {object} Custom cache keys object for cache invalidation
23
* @default (defaultCacheKeys) => defaultCacheKeys
24
*/
25
cacheKeys: (defaultCacheKeys: object, file: string) => object;
26
```
27
28
**Cache Configuration Examples:**
29
30
```javascript
31
new UglifyJsPlugin({
32
// Enable caching with default directory: node_modules/.cache/uglifyjs-webpack-plugin
33
cache: true,
34
35
// Custom cache directory
36
cache: '/path/to/custom/cache',
37
38
// Custom cache keys for advanced cache invalidation
39
cacheKeys: (defaultCacheKeys, file) => ({
40
...defaultCacheKeys,
41
buildVersion: process.env.BUILD_VERSION,
42
customConfig: myCustomConfig,
43
}),
44
})
45
```
46
47
**Default Cache Keys:**
48
- `'uglify-js'`: UglifyJS package version
49
- `'uglifyjs-webpack-plugin'`: Plugin version
50
- `'uglifyjs-webpack-plugin-options'`: Plugin configuration hash
51
- `hash`: MD4 hash of input file content
52
- `node_version`: Node.js version
53
54
**Cache Behavior:**
55
- Cache hits skip minification and return cached results
56
- Cache misses trigger minification and store results
57
- Cache invalidation occurs when any cache key changes
58
- Cached results include: `code`, `map`, `warnings`, `extractedComments`
59
60
### Parallel Processing
61
62
Multi-process parallel execution for improved build performance on multi-core systems.
63
64
```javascript { .api }
65
/**
66
* Use multi-process parallel running to improve build speed
67
* @type {boolean | number}
68
* @default false
69
*/
70
parallel: boolean | number;
71
```
72
73
**Parallel Configuration Examples:**
74
75
```javascript
76
new UglifyJsPlugin({
77
// Enable parallel processing (uses os.cpus().length - 1 workers)
78
parallel: true,
79
80
// Custom number of parallel workers
81
parallel: 4,
82
83
// Disable parallel processing
84
parallel: false,
85
})
86
```
87
88
**Parallel Processing Details:**
89
90
- **Worker Farm**: Uses `worker-farm` package for process management
91
- **Default Workers**: `os.cpus().length - 1` (leaves one CPU core free)
92
- **WSL Limitation**: Forced to single worker on Windows Subsystem for Linux
93
- **Windows Optimization**: Uses `maxConcurrentCallsPerWorker: 1` for stability
94
- **Task Distribution**: Distributes file processing tasks across worker processes
95
- **Memory Management**: Each worker process handles serialized task data
96
97
**Performance Considerations:**
98
- Most effective with large numbers of files (>10)
99
- Overhead costs may outweigh benefits for small bundles
100
- Combines well with caching for optimal performance
101
- Memory usage increases with worker count
102
103
### Custom Minification Functions
104
105
Replace default UglifyJS with custom minification implementations for specialized use cases.
106
107
```javascript { .api }
108
/**
109
* Custom minify function to override default UglifyJS behavior
110
* Must return MinifyResult object with expected properties
111
* Always use require() inside function when parallel processing is enabled
112
* @param {object} file - Object with filename as key and source as value
113
* @param {object} sourceMap - Input source map object (if available)
114
* @returns {MinifyResult} Minification result with code, map, warnings, etc.
115
*/
116
minify: (file: object, sourceMap?: object) => MinifyResult;
117
118
interface MinifyResult {
119
/** Minification error (if any) */
120
error?: Error;
121
/** Generated source map string */
122
map?: string;
123
/** Minified code string */
124
code?: string;
125
/** Array of warning messages */
126
warnings?: string[];
127
/** Array of extracted comment strings */
128
extractedComments?: string[];
129
}
130
```
131
132
**Custom Minification Examples:**
133
134
**Using Terser (UglifyJS alternative):**
135
```javascript
136
new UglifyJsPlugin({
137
minify(file, sourceMap) {
138
const terserOptions = {
139
compress: {
140
drop_console: true,
141
},
142
mangle: true,
143
};
144
145
if (sourceMap) {
146
terserOptions.sourceMap = {
147
content: sourceMap,
148
};
149
}
150
151
return require('terser').minify(file, terserOptions);
152
},
153
})
154
```
155
156
**Using esbuild for faster minification:**
157
```javascript
158
new UglifyJsPlugin({
159
minify(file, sourceMap) {
160
const esbuild = require('esbuild');
161
const filename = Object.keys(file)[0];
162
const source = file[filename];
163
164
try {
165
const result = esbuild.transformSync(source, {
166
minify: true,
167
sourcemap: !!sourceMap,
168
});
169
170
return {
171
code: result.code,
172
map: result.map,
173
warnings: [],
174
extractedComments: [],
175
};
176
} catch (error) {
177
return {
178
error: error,
179
};
180
}
181
},
182
})
183
```
184
185
**Using custom preprocessing:**
186
```javascript
187
new UglifyJsPlugin({
188
minify(file, sourceMap) {
189
const uglify = require('uglify-js');
190
const filename = Object.keys(file)[0];
191
let source = file[filename];
192
193
// Custom preprocessing
194
source = source.replace(/console\.debug\([^)]*\);?/g, '');
195
source = source.replace(/\/\*\s*@debug\s*\*\/[\s\S]*?\/\*\s*@\/debug\s*\*\//g, '');
196
197
const options = {
198
compress: {
199
drop_console: false, // We already removed debug console calls
200
},
201
sourceMap: sourceMap ? { content: sourceMap } : false,
202
};
203
204
return uglify.minify({ [filename]: source }, options);
205
},
206
})
207
```
208
209
**Important Notes for Custom Minification:**
210
- Always use `require()` inside the function when `parallel: true`
211
- Must return object with `MinifyResult` interface
212
- Handle errors by returning `{ error: Error }` object
213
- Source map handling is optional but recommended
214
- Function is serialized for worker processes (no closure variables)
215
216
### Cache Invalidation Strategies
217
218
Advanced cache key customization for complex build scenarios.
219
220
```javascript { .api }
221
/**
222
* Advanced cache key customization for complex invalidation scenarios
223
* @param {object} defaultCacheKeys - Plugin's default cache keys
224
* @param {string} file - Current file path being processed
225
* @returns {object} Enhanced cache keys object
226
*/
227
cacheKeys: (defaultCacheKeys: object, file: string) => object;
228
```
229
230
**Cache Invalidation Examples:**
231
232
**Environment-based invalidation:**
233
```javascript
234
new UglifyJsPlugin({
235
cache: true,
236
cacheKeys: (defaultCacheKeys, file) => ({
237
...defaultCacheKeys,
238
nodeEnv: process.env.NODE_ENV,
239
buildId: process.env.BUILD_ID,
240
gitCommit: process.env.GIT_COMMIT,
241
}),
242
})
243
```
244
245
**File-specific invalidation:**
246
```javascript
247
new UglifyJsPlugin({
248
cache: true,
249
cacheKeys: (defaultCacheKeys, file) => {
250
const keys = { ...defaultCacheKeys };
251
252
// Different cache strategy for vendor vs app files
253
if (file.includes('vendor')) {
254
keys.vendorVersion = require('./package.json').dependencies;
255
} else {
256
keys.appVersion = require('./package.json').version;
257
}
258
259
return keys;
260
},
261
})
262
```
263
264
**Configuration-based invalidation:**
265
```javascript
266
new UglifyJsPlugin({
267
cache: true,
268
cacheKeys: (defaultCacheKeys, file) => ({
269
...defaultCacheKeys,
270
webpackConfig: crypto
271
.createHash('md5')
272
.update(JSON.stringify(webpackConfig))
273
.digest('hex'),
274
customMinifyOptions: JSON.stringify(customOptions),
275
}),
276
})
277
```
278
279
### Performance Optimization Patterns
280
281
Recommended configurations for different build scenarios.
282
283
**Development builds (fast iteration):**
284
```javascript
285
new UglifyJsPlugin({
286
cache: true,
287
parallel: true,
288
sourceMap: true,
289
uglifyOptions: {
290
warnings: false,
291
compress: false,
292
mangle: false,
293
},
294
})
295
```
296
297
**Production builds (maximum optimization):**
298
```javascript
299
new UglifyJsPlugin({
300
cache: true,
301
parallel: true,
302
sourceMap: false,
303
extractComments: true,
304
uglifyOptions: {
305
compress: {
306
drop_console: true,
307
drop_debugger: true,
308
pure_funcs: ['console.log', 'console.info'],
309
},
310
mangle: {
311
toplevel: true,
312
},
313
output: {
314
comments: false,
315
},
316
},
317
})
318
```
319
320
**CI/CD builds (reproducible and cached):**
321
```javascript
322
new UglifyJsPlugin({
323
cache: '/shared/cache/uglifyjs',
324
parallel: Math.min(4, os.cpus().length - 1),
325
cacheKeys: (defaultCacheKeys) => ({
326
...defaultCacheKeys,
327
buildNumber: process.env.BUILD_NUMBER,
328
nodeVersion: process.version,
329
}),
330
})
331
```