UNPKG

12.4 kBMarkdownView Raw
1<div align="center">
2 <a href="https://github.com/webpack/webpack">
3 <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg">
4 </a>
5</div>
6
7[![npm][npm]][npm-url]
8[![node][node]][node-url]
9[![deps][deps]][deps-url]
10[![tests][tests]][tests-url]
11[![cover][cover]][cover-url]
12[![chat][chat]][chat-url]
13[![size][size]][size-url]
14
15# UglifyJS Webpack Plugin
16
17This plugin uses [uglify-js](https://github.com/mishoo/UglifyJS2) to minify your JavaScript.
18
19## Requirements
20
21This module requires a minimum of Node v6.9.0 and Webpack v4.0.0.
22
23## Getting Started
24
25To begin, you'll need to install `uglifyjs-webpack-plugin`:
26
27```console
28$ npm install uglifyjs-webpack-plugin --save-dev
29```
30
31Then add the plugin to your `webpack` config. For example:
32
33**webpack.config.js**
34
35```js
36const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
37
38module.exports = {
39 //...
40 optimization: {
41 minimizer: [new UglifyJsPlugin()]
42 }
43};
44```
45
46And run `webpack` via your preferred method.
47
48## Options
49
50### `test`
51
52Type: `String|RegExp|Array<String|RegExp>`
53Default: `/\.js(\?.*)?$/i`
54
55Test to match files against.
56
57```js
58// in your webpack.config.js
59new UglifyJsPlugin({
60 test: /\.js(\?.*)?$/i
61})
62```
63
64### `include`
65
66Type: `String|RegExp|Array<String|RegExp>`
67Default: `undefined`
68
69Files to include.
70
71```js
72// in your webpack.config.js
73new UglifyJsPlugin({
74 include: /\/includes/
75})
76```
77
78### `exclude`
79
80Type: `String|RegExp|Array<String|RegExp>`
81Default: `undefined`
82
83Files to exclude.
84
85```js
86// in your webpack.config.js
87new UglifyJsPlugin({
88 exclude: /\/excludes/
89})
90```
91
92### `cache`
93
94Type: `Boolean|String`
95Default: `false`
96
97Enable file caching.
98Default path to cache directory: `node_modules/.cache/uglifyjs-webpack-plugin`.
99
100> ℹ️ If you use your own `minify` function please read the `minify` section for cache invalidation correctly.
101
102#### `Boolean`
103
104Enable/disable file caching.
105
106```js
107// in your webpack.config.js
108new UglifyJsPlugin({
109 cache: true
110})
111```
112
113#### `String`
114
115Enable file caching and set path to cache directory.
116
117**webpack.config.js**
118
119```js
120// in your webpack.config.js
121new UglifyJsPlugin({
122 cache: 'path/to/cache'
123})
124```
125
126### `cacheKeys`
127
128Type: `Function<(defaultCacheKeys, file) -> Object>`
129Default: `defaultCacheKeys => defaultCacheKeys`
130
131Allows you to override default cache keys.
132
133Default cache keys:
134
135```js
136({
137 'uglify-js': require('uglify-js/package.json').version, // uglify version
138 'uglifyjs-webpack-plugin': require('../package.json').version, // plugin version
139 'uglifyjs-webpack-plugin-options': this.options, // plugin options
140 path: compiler.outputPath ? `${compiler.outputPath}/${file}` : file, // asset path
141 hash: crypto.createHash('md4').update(input).digest('hex'), // source file hash
142});
143```
144
145```js
146// in your webpack.config.js
147new UglifyJsPlugin({
148 cache: true,
149 cacheKeys: (defaultCacheKeys, file) => {
150 defaultCacheKeys.myCacheKey = 'myCacheKeyValue';
151
152 return defaultCacheKeys;
153 },
154})
155```
156
157### `parallel`
158
159Type: `Boolean|Number`
160Default: `false`
161
162Use multi-process parallel running to improve the build speed.
163Default number of concurrent runs: `os.cpus().length - 1`.
164
165> ℹ️ Parallelization can speedup your build significantly and is therefore **highly recommended**.
166
167#### `Boolean`
168
169Enable/disable multi-process parallel running.
170
171```js
172// in your webpack.config.js
173new UglifyJsPlugin({
174 parallel: true
175})
176```
177
178#### `Number`
179
180Enable multi-process parallel running and set number of concurrent runs.
181
182```js
183// in your webpack.config.js
184new UglifyJsPlugin({
185 parallel: 4
186})
187```
188
189### `sourceMap`
190
191Type: `Boolean`
192Default: `false`
193
194Use source maps to map error message locations to modules (this slows down the compilation).
195If you use your own `minify` function please read the `minify` section for handling source maps correctly.
196
197> ⚠️ **`cheap-source-map` options don't work with this plugin**.
198
199```js
200// in your webpack.config.js
201new UglifyJsPlugin({
202 sourceMap: true
203})
204```
205
206### `minify`
207
208Type: `Function`
209Default: `undefined`
210
211Allows you to override default minify function.
212By default plugin uses [uglify-js](https://github.com/mishoo/UglifyJS2) package.
213Useful for using and testing unpublished versions or forks.
214
215> ⚠️ **Always use `require` inside `minify` function when `parallel` option enabled**.
216
217```js
218// in your webpack.config.js
219new UglifyJsPlugin({
220 minify(file, sourceMap) {
221 const extractedComments = [];
222
223 // Custom logic for extract comments
224
225 const { error, map, code, warnings } = require('uglify-module') // Or require('./path/to/uglify-module')
226 .minify(file, {
227 /* Your options for minification */
228 });
229
230 return { error, map, code, warnings, extractedComments };
231 }
232})
233```
234
235### `uglifyOptions`
236
237Type: `Object`
238Default: [default](https://github.com/mishoo/UglifyJS2#minify-options)
239
240UglifyJS minify options.
241
242```js
243// in your webpack.config.js
244new UglifyJsPlugin({
245 uglifyOptions: {
246 warnings: false,
247 parse: {},
248 compress: {},
249 mangle: true, // Note `mangle.properties` is `false` by default.
250 output: null,
251 toplevel: false,
252 nameCache: null,
253 ie8: false,
254 keep_fnames: false,
255 }
256})
257```
258
259### `extractComments`
260
261Type: `Boolean|String|RegExp|Function<(node, comment) -> Boolean|Object>`
262Default: `false`
263
264Whether comments shall be extracted to a separate file, (see [details](https://github.com/webpack/webpack/commit/71933e979e51c533b432658d5e37917f9e71595a)).
265By default extract only comments using `/^\**!|@preserve|@license|@cc_on/i` regexp condition and remove remaining comments.
266If the original file is named `foo.js`, then the comments will be stored to `foo.js.LICENSE`.
267The `uglifyOptions.output.comments` option specifies whether the comment will be preserved, i.e. it is possible to preserve some comments (e.g. annotations) while extracting others or even preserving comments that have been extracted.
268
269#### `Boolean`
270
271Enable/disable extracting comments.
272
273```js
274// in your webpack.config.js
275new UglifyJsPlugin({
276 extractComments: true
277})
278```
279
280#### `String`
281
282Extract `all` or `some` (use `/^\**!|@preserve|@license|@cc_on/i` RegExp) comments.
283
284```js
285// in your webpack.config.js
286new UglifyJsPlugin({
287 extractComments: 'all'
288})
289```
290
291#### `RegExp`
292
293All comments that match the given expression will be extracted to the separate file.
294
295```js
296// in your webpack.config.js
297new UglifyJsPlugin({
298 extractComments: /@extract/i
299})
300```
301
302#### `Function<(node, comment) -> Boolean>`
303
304All comments that match the given expression will be extracted to the separate file.
305
306```js
307// in your webpack.config.js
308new UglifyJsPlugin({
309 extractComments: function (astNode, comment) {
310 if (/@extract/i.test(comment.value)) {
311 return true;
312 }
313
314 return false;
315 }
316})
317```
318
319#### `Object`
320
321Allow to customize condition for extract comments, specify extracted file name and banner.
322
323```js
324// in your webpack.config.js
325new UglifyJsPlugin({
326 extractComments: {
327 condition: /^\**!|@preserve|@license|@cc_on/i,
328 filename(file) {
329 return `${file}.LICENSE`;
330 },
331 banner(licenseFile) {
332 return `License information can be found in ${licenseFile}`;
333 }
334 }
335})
336```
337
338##### `condition`
339
340Type: `Boolean|String|RegExp|Function<(node, comment) -> Boolean|Object>`
341
342Condition what comments you need extract.
343
344```js
345// in your webpack.config.js
346new UglifyJsPlugin({
347 extractComments: {
348 condition: 'some',
349 filename(file) {
350 return `${file}.LICENSE`;
351 },
352 banner(licenseFile) {
353 return `License information can be found in ${licenseFile}`;
354 }
355 }
356})
357```
358
359##### `filename`
360
361Type: `Regex|Function<(string) -> String>`
362Default: `${file}.LICENSE`
363
364The file where the extracted comments will be stored.
365Default is to append the suffix `.LICENSE` to the original filename.
366
367```js
368// in your webpack.config.js
369new UglifyJsPlugin({
370 extractComments: {
371 condition: /^\**!|@preserve|@license|@cc_on/i,
372 filename: 'extracted-comments.js',
373 banner(licenseFile) {
374 return `License information can be found in ${licenseFile}`;
375 }
376 }
377})
378```
379
380##### `banner`
381
382Type: `Boolean|String|Function<(string) -> String>`
383Default: `/*! For license information please see ${commentsFile} */`
384
385The banner text that points to the extracted file and will be added on top of the original file.
386Can be `false` (no banner), a `String`, or a `Function<(string) -> String>` that will be called with the filename where extracted comments have been stored.
387Will be wrapped into comment.
388
389```js
390// in your webpack.config.js
391new UglifyJsPlugin({
392 extractComments: {
393 condition: true,
394 filename(file) {
395 return `${file}.LICENSE`;
396 },
397 banner(commentsFile) {
398 return `My custom banner about license information ${commentsFile}`;
399 }
400 }
401})
402```
403
404### `warningsFilter`
405
406Type: `Function<(warning, source) -> Boolean>`
407Default: `() => true`
408
409Allow to filter [uglify-js](https://github.com/mishoo/UglifyJS2) warnings.
410Return `true` to keep the warning, `false` otherwise.
411
412```js
413// in your webpack.config.js
414new UglifyJsPlugin({
415 warningsFilter: (warning, source) => {
416 if (/Dropping unreachable code/i.test(warning)) {
417 return true;
418 }
419
420 if (/filename\.js/i.test(source)) {
421 return true;
422 }
423
424 return false;
425 },
426})
427```
428
429## Examples
430
431### Cache And Parallel
432
433Enable cache and multi-process parallel running.
434
435```js
436// in your webpack.config.js
437const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
438
439module.exports = {
440 //...
441 optimization: {
442 minimizer: [
443 new UglifyJsPlugin({
444 cache: true,
445 parallel: true
446 })
447 ]
448 }
449};
450```
451
452### Preserve Comments
453
454Extract all legal comments (i.e. `/^\**!|@preserve|@license|@cc_on/i`) and preserve `/@license/i` comments.
455
456```js
457// in your webpack.config.js
458const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
459
460module.exports = {
461 //...
462 optimization: {
463 minimizer: [
464 new UglifyJsPlugin({
465 uglifyOptions: {
466 output: {
467 comments: /@license/i
468 }
469 },
470 extractComments: true
471 })
472 ]
473 }
474};
475```
476
477### Custom Minify Function
478
479Override default minify function - use [terser](https://github.com/fabiosantoscode/terser) for minification.
480
481```js
482// in your webpack.config.js
483const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
484
485module.exports = {
486 //...
487 optimization: {
488 minimizer: [
489 new UglifyJsPlugin({
490 // Uncomment lines below for cache invalidation correctly
491 // cache: true,
492 // cacheKeys(defaultCacheKeys) {
493 // delete defaultCacheKeys['uglify-js'];
494 //
495 // return Object.assign(
496 // {},
497 // defaultCacheKeys,
498 // { 'uglify-js': require('uglify-js/package.json').version },
499 // );
500 // },
501 minify(file, sourceMap) {
502 // https://github.com/mishoo/UglifyJS2#minify-options
503 const uglifyJsOptions = {
504 /* your `uglify-js` package options */
505 };
506
507 if (sourceMap) {
508 uglifyJsOptions.sourceMap = {
509 content: sourceMap,
510 };
511 }
512
513 return require('terser').minify(file, uglifyJsOptions);
514 },
515 })
516 ]
517 }
518};
519```
520
521## Contributing
522
523Please take a moment to read our contributing guidelines if you haven't yet done so.
524
525[CONTRIBUTING](./.github/CONTRIBUTING.md)
526
527## License
528
529[MIT](./LICENSE)
530
531[npm]: https://img.shields.io/npm/v/uglifyjs-webpack-plugin.svg
532[npm-url]: https://npmjs.com/package/uglifyjs-webpack-plugin
533[node]: https://img.shields.io/node/v/uglifyjs-webpack-plugin.svg
534[node-url]: https://nodejs.org
535[deps]: https://david-dm.org/webpack-contrib/uglifyjs-webpack-plugin.svg
536[deps-url]: https://david-dm.org/webpack-contrib/uglifyjs-webpack-plugin
537[tests]: https://img.shields.io/circleci/project/github/webpack-contrib/uglifyjs-webpack-plugin.svg
538[tests-url]: https://circleci.com/gh/webpack-contrib/uglifyjs-webpack-plugin
539[cover]: https://codecov.io/gh/webpack-contrib/uglifyjs-webpack-plugin/branch/master/graph/badge.svg
540[cover-url]: https://codecov.io/gh/webpack-contrib/uglifyjs-webpack-plugin
541[chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg
542[chat-url]: https://gitter.im/webpack/webpack
543[size]: https://packagephobia.now.sh/badge?p=uglifyjs-webpack-plugin
544[size-url]: https://packagephobia.now.sh/result?p=uglifyjs-webpack-plugin