Projekt

Obecné

Profil

Stáhnout (15 KB) Statistiky
| Větev: | Revize:
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
# terser-webpack-plugin
16

    
17
This plugin uses [terser](https://github.com/terser-js/terser) to minify your JavaScript.
18

    
19
> ℹ️ For `webpack@3` use [terser-webpack-plugin-legacy](https://www.npmjs.com/package/terser-webpack-plugin-legacy) package
20

    
21
## Getting Started
22

    
23
To begin, you'll need to install `terser-webpack-plugin`:
24

    
25
```console
26
$ npm install terser-webpack-plugin --save-dev
27
```
28

    
29
Then add the plugin to your `webpack` config. For example:
30

    
31
**webpack.config.js**
32

    
33
```js
34
const TerserPlugin = require('terser-webpack-plugin');
35

    
36
module.exports = {
37
  optimization: {
38
    minimizer: [new TerserPlugin()],
39
  },
40
};
41
```
42

    
43
And run `webpack` via your preferred method.
44

    
45
## Options
46

    
47
### `test`
48

    
49
Type: `String|RegExp|Array<String|RegExp>`
50
Default: `/\.m?js(\?.*)?$/i`
51

    
52
Test to match files against.
53

    
54
**webpack.config.js**
55

    
56
```js
57
module.exports = {
58
  optimization: {
59
    minimizer: [
60
      new TerserPlugin({
61
        test: /\.js(\?.*)?$/i,
62
      }),
63
    ],
64
  },
65
};
66
```
67

    
68
### `include`
69

    
70
Type: `String|RegExp|Array<String|RegExp>`
71
Default: `undefined`
72

    
73
Files to include.
74

    
75
**webpack.config.js**
76

    
77
```js
78
module.exports = {
79
  optimization: {
80
    minimizer: [
81
      new TerserPlugin({
82
        include: /\/includes/,
83
      }),
84
    ],
85
  },
86
};
87
```
88

    
89
### `exclude`
90

    
91
Type: `String|RegExp|Array<String|RegExp>`
92
Default: `undefined`
93

    
94
Files to exclude.
95

    
96
**webpack.config.js**
97

    
98
```js
99
module.exports = {
100
  optimization: {
101
    minimizer: [
102
      new TerserPlugin({
103
        exclude: /\/excludes/,
104
      }),
105
    ],
106
  },
107
};
108
```
109

    
110
### `chunkFilter`
111

    
112
Type: `Function<(chunk) -> boolean>`
113
Default: `() => true`
114

    
115
Allowing to filter which chunks should be uglified (by default all chunks are uglified).
116
Return `true` to uglify the chunk, `false` otherwise.
117

    
118
**webpack.config.js**
119

    
120
```js
121
module.exports = {
122
  optimization: {
123
    minimizer: [
124
      new TerserPlugin({
125
        chunkFilter: (chunk) => {
126
          // Exclude uglification for the `vendor` chunk
127
          if (chunk.name === 'vendor') {
128
            return false;
129
          }
130

    
131
          return true;
132
        },
133
      }),
134
    ],
135
  },
136
};
137
```
138

    
139
### `cache`
140

    
141
Type: `Boolean|String`
142
Default: `false`
143

    
144
Enable file caching.
145
Default path to cache directory: `node_modules/.cache/terser-webpack-plugin`.
146

    
147
> ℹ️ If you use your own `minify` function please read the `minify` section for cache invalidation correctly.
148

    
149
#### `Boolean`
150

    
151
Enable/disable file caching.
152

    
153
**webpack.config.js**
154

    
155
```js
156
module.exports = {
157
  optimization: {
158
    minimizer: [
159
      new TerserPlugin({
160
        cache: true,
161
      }),
162
    ],
163
  },
164
};
165
```
166

    
167
#### `String`
168

    
169
Enable file caching and set path to cache directory.
170

    
171
**webpack.config.js**
172

    
173
```js
174
module.exports = {
175
  optimization: {
176
    minimizer: [
177
      new TerserPlugin({
178
        cache: 'path/to/cache',
179
      }),
180
    ],
181
  },
182
};
183
```
184

    
185
### `cacheKeys`
186

    
187
Type: `Function<(defaultCacheKeys, file) -> Object>`
188
Default: `defaultCacheKeys => defaultCacheKeys`
189

    
190
Allows you to override default cache keys.
191

    
192
Default cache keys:
193

    
194
```js
195
({
196
  terser: require('terser/package.json').version, // terser version
197
  'terser-webpack-plugin': require('../package.json').version, // plugin version
198
  'terser-webpack-plugin-options': this.options, // plugin options
199
  path: compiler.outputPath ? `${compiler.outputPath}/${file}` : file, // asset path
200
  hash: crypto
201
    .createHash('md4')
202
    .update(input)
203
    .digest('hex'), // source file hash
204
});
205
```
206

    
207
**webpack.config.js**
208

    
209
```js
210
module.exports = {
211
  optimization: {
212
    minimizer: [
213
      new TerserPlugin({
214
        cache: true,
215
        cacheKeys: (defaultCacheKeys, file) => {
216
          defaultCacheKeys.myCacheKey = 'myCacheKeyValue';
217

    
218
          return defaultCacheKeys;
219
        },
220
      }),
221
    ],
222
  },
223
};
224
```
225

    
226
### `parallel`
227

    
228
Type: `Boolean|Number`
229
Default: `false`
230

    
231
Use multi-process parallel running to improve the build speed.
232
Default number of concurrent runs: `os.cpus().length - 1`.
233

    
234
> ℹ️ Parallelization can speedup your build significantly and is therefore **highly recommended**.
235

    
236
#### `Boolean`
237

    
238
Enable/disable multi-process parallel running.
239

    
240
**webpack.config.js**
241

    
242
```js
243
module.exports = {
244
  optimization: {
245
    minimizer: [
246
      new TerserPlugin({
247
        parallel: true,
248
      }),
249
    ],
250
  },
251
};
252
```
253

    
254
#### `Number`
255

    
256
Enable multi-process parallel running and set number of concurrent runs.
257

    
258
**webpack.config.js**
259

    
260
```js
261
module.exports = {
262
  optimization: {
263
    minimizer: [
264
      new TerserPlugin({
265
        parallel: 4,
266
      }),
267
    ],
268
  },
269
};
270
```
271

    
272
### `sourceMap`
273

    
274
Type: `Boolean`
275
Default: `false`
276

    
277
Use source maps to map error message locations to modules (this slows down the compilation).
278
If you use your own `minify` function please read the `minify` section for handling source maps correctly.
279

    
280
> ⚠️ **`cheap-source-map` options don't work with this plugin**.
281

    
282
**webpack.config.js**
283

    
284
```js
285
module.exports = {
286
  optimization: {
287
    minimizer: [
288
      new TerserPlugin({
289
        sourceMap: true,
290
      }),
291
    ],
292
  },
293
};
294
```
295

    
296
### `minify`
297

    
298
Type: `Function`
299
Default: `undefined`
300

    
301
Allows you to override default minify function.
302
By default plugin uses [terser](https://github.com/terser-js/terser) package.
303
Useful for using and testing unpublished versions or forks.
304

    
305
> ⚠️ **Always use `require` inside `minify` function when `parallel` option enabled**.
306

    
307
**webpack.config.js**
308

    
309
```js
310
module.exports = {
311
  optimization: {
312
    minimizer: [
313
      new TerserPlugin({
314
        minify: (file, sourceMap) => {
315
          const extractedComments = [];
316

    
317
          // Custom logic for extract comments
318

    
319
          const { error, map, code, warnings } = require('uglify-module') // Or require('./path/to/uglify-module')
320
            .minify(file, {
321
              /* Your options for minification */
322
            });
323

    
324
          return { error, map, code, warnings, extractedComments };
325
        },
326
      }),
327
    ],
328
  },
329
};
330
```
331

    
332
### `terserOptions`
333

    
334
Type: `Object`
335
Default: [default](https://github.com/terser-js/terser#minify-options)
336

    
337
Terser minify [options](https://github.com/terser-js/terser#minify-options).
338

    
339
**webpack.config.js**
340

    
341
```js
342
module.exports = {
343
  optimization: {
344
    minimizer: [
345
      new TerserPlugin({
346
        terserOptions: {
347
          ecma: undefined,
348
          warnings: false,
349
          parse: {},
350
          compress: {},
351
          mangle: true, // Note `mangle.properties` is `false` by default.
352
          module: false,
353
          output: null,
354
          toplevel: false,
355
          nameCache: null,
356
          ie8: false,
357
          keep_classnames: undefined,
358
          keep_fnames: false,
359
          safari10: false,
360
        },
361
      }),
362
    ],
363
  },
364
};
365
```
366

    
367
### `extractComments`
368

    
369
Type: `Boolean|String|RegExp|Function<(node, comment) -> Boolean|Object>|Object`
370
Default: `false`
371

    
372
Whether comments shall be extracted to a separate file, (see [details](https://github.com/webpack/webpack/commit/71933e979e51c533b432658d5e37917f9e71595a)).
373
By default extract only comments using `/^\**!|@preserve|@license|@cc_on/i` regexp condition and remove remaining comments.
374
If the original file is named `foo.js`, then the comments will be stored to `foo.js.LICENSE`.
375
The `terserOptions.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.
376

    
377
#### `Boolean`
378

    
379
Enable/disable extracting comments.
380

    
381
**webpack.config.js**
382

    
383
```js
384
module.exports = {
385
  optimization: {
386
    minimizer: [
387
      new TerserPlugin({
388
        extractComments: true,
389
      }),
390
    ],
391
  },
392
};
393
```
394

    
395
#### `String`
396

    
397
Extract `all` or `some` (use `/^\**!|@preserve|@license|@cc_on/i` RegExp) comments.
398

    
399
**webpack.config.js**
400

    
401
```js
402
module.exports = {
403
  optimization: {
404
    minimizer: [
405
      new TerserPlugin({
406
        extractComments: 'all',
407
      }),
408
    ],
409
  },
410
};
411
```
412

    
413
#### `RegExp`
414

    
415
All comments that match the given expression will be extracted to the separate file.
416

    
417
**webpack.config.js**
418

    
419
```js
420
module.exports = {
421
  optimization: {
422
    minimizer: [
423
      new TerserPlugin({
424
        extractComments: /@extract/i,
425
      }),
426
    ],
427
  },
428
};
429
```
430

    
431
#### `Function<(node, comment) -> Boolean>`
432

    
433
All comments that match the given expression will be extracted to the separate file.
434

    
435
**webpack.config.js**
436

    
437
```js
438
module.exports = {
439
  optimization: {
440
    minimizer: [
441
      new TerserPlugin({
442
        extractComments: (astNode, comment) => {
443
          if (/@extract/i.test(comment.value)) {
444
            return true;
445
          }
446

    
447
          return false;
448
        },
449
      }),
450
    ],
451
  },
452
};
453
```
454

    
455
#### `Object`
456

    
457
Allow to customize condition for extract comments, specify extracted file name and banner.
458

    
459
**webpack.config.js**
460

    
461
```js
462
module.exports = {
463
  optimization: {
464
    minimizer: [
465
      new TerserPlugin({
466
        extractComments: {
467
          condition: /^\**!|@preserve|@license|@cc_on/i,
468
          filename: (file) => {
469
            return `${file}.LICENSE`;
470
          },
471
          banner: (licenseFile) => {
472
            return `License information can be found in ${licenseFile}`;
473
          },
474
        },
475
      }),
476
    ],
477
  },
478
};
479
```
480

    
481
##### `condition`
482

    
483
Type: `Boolean|String|RegExp|Function<(node, comment) -> Boolean|Object>`
484

    
485
Condition what comments you need extract.
486

    
487
**webpack.config.js**
488

    
489
```js
490
module.exports = {
491
  optimization: {
492
    minimizer: [
493
      new TerserPlugin({
494
        extractComments: {
495
          condition: 'some',
496
          filename: (file) => {
497
            return `${file}.LICENSE`;
498
          },
499
          banner: (licenseFile) => {
500
            return `License information can be found in ${licenseFile}`;
501
          },
502
        },
503
      }),
504
    ],
505
  },
506
};
507
```
508

    
509
##### `filename`
510

    
511
Type: `String|Function<(string) -> String>`
512
Default: `${file}.LICENSE`
513

    
514
The file where the extracted comments will be stored.
515
Default is to append the suffix `.LICENSE` to the original filename.
516

    
517
**webpack.config.js**
518

    
519
```js
520
module.exports = {
521
  optimization: {
522
    minimizer: [
523
      new TerserPlugin({
524
        extractComments: {
525
          condition: /^\**!|@preserve|@license|@cc_on/i,
526
          filename: 'extracted-comments.js',
527
          banner: (licenseFile) => {
528
            return `License information can be found in ${licenseFile}`;
529
          },
530
        },
531
      }),
532
    ],
533
  },
534
};
535
```
536

    
537
##### `banner`
538

    
539
Type: `Boolean|String|Function<(string) -> String>`
540
Default: `/*! For license information please see ${commentsFile} */`
541

    
542
The banner text that points to the extracted file and will be added on top of the original file.
543
Can be `false` (no banner), a `String`, or a `Function<(string) -> String>` that will be called with the filename where extracted comments have been stored.
544
Will be wrapped into comment.
545

    
546
**webpack.config.js**
547

    
548
```js
549
module.exports = {
550
  optimization: {
551
    minimizer: [
552
      new TerserPlugin({
553
        extractComments: {
554
          condition: true,
555
          filename: (file) => {
556
            return `${file}.LICENSE`;
557
          },
558
          banner: (commentsFile) => {
559
            return `My custom banner about license information ${commentsFile}`;
560
          },
561
        },
562
      }),
563
    ],
564
  },
565
};
566
```
567

    
568
### `warningsFilter`
569

    
570
Type: `Function<(warning, source) -> Boolean>`
571
Default: `() => true`
572

    
573
Allow to filter [terser](https://github.com/terser-js/terser) warnings.
574
Return `true` to keep the warning, `false` otherwise.
575

    
576
**webpack.config.js**
577

    
578
```js
579
module.exports = {
580
  optimization: {
581
    minimizer: [
582
      new TerserPlugin({
583
        warningsFilter: (warning, source) => {
584
          if (/Dropping unreachable code/i.test(warning)) {
585
            return true;
586
          }
587

    
588
          if (/filename\.js/i.test(source)) {
589
            return true;
590
          }
591

    
592
          return false;
593
        },
594
      }),
595
    ],
596
  },
597
};
598
```
599

    
600
## Examples
601

    
602
### Cache And Parallel
603

    
604
Enable cache and multi-process parallel running.
605

    
606
**webpack.config.js**
607

    
608
```js
609
module.exports = {
610
  optimization: {
611
    minimizer: [
612
      new TerserPlugin({
613
        cache: true,
614
        parallel: true,
615
      }),
616
    ],
617
  },
618
};
619
```
620

    
621
### Preserve Comments
622

    
623
Extract all legal comments (i.e. `/^\**!|@preserve|@license|@cc_on/i`) and preserve `/@license/i` comments.
624

    
625
**webpack.config.js**
626

    
627
```js
628
module.exports = {
629
  optimization: {
630
    minimizer: [
631
      new TerserPlugin({
632
        terserOptions: {
633
          output: {
634
            comments: /@license/i,
635
          },
636
        },
637
        extractComments: true,
638
      }),
639
    ],
640
  },
641
};
642
```
643

    
644
### Remove Comments
645

    
646
If you avoid building with comments, set **terserOptions.output.comments** to **false** as in this config:
647

    
648
**webpack.config.js**
649

    
650
```js
651
module.exports = {
652
  optimization: {
653
    minimizer: [
654
      new TerserPlugin({
655
        terserOptions: {
656
          output: {
657
            comments: false,
658
          },
659
        },
660
      }),
661
    ],
662
  },
663
};
664
```
665

    
666
### Custom Minify Function
667

    
668
Override default minify function - use `uglify-js` for minification.
669

    
670
**webpack.config.js**
671

    
672
```js
673
module.exports = {
674
  optimization: {
675
    minimizer: [
676
      new TerserPlugin({
677
        // Uncomment lines below for cache invalidation correctly
678
        // cache: true,
679
        // cacheKeys: (defaultCacheKeys) => {
680
        //   delete defaultCacheKeys.terser;
681
        //
682
        //   return Object.assign(
683
        //     {},
684
        //     defaultCacheKeys,
685
        //     { 'uglify-js': require('uglify-js/package.json').version },
686
        //   );
687
        // },
688
        minify: (file, sourceMap) => {
689
          // https://github.com/mishoo/UglifyJS2#minify-options
690
          const uglifyJsOptions = {
691
            /* your `uglify-js` package options */
692
          };
693

    
694
          if (sourceMap) {
695
            uglifyJsOptions.sourceMap = {
696
              content: sourceMap,
697
            };
698
          }
699

    
700
          return require('uglify-js').minify(file, uglifyJsOptions);
701
        },
702
      }),
703
    ],
704
  },
705
};
706
```
707

    
708
## Contributing
709

    
710
Please take a moment to read our contributing guidelines if you haven't yet done so.
711

    
712
[CONTRIBUTING](./.github/CONTRIBUTING.md)
713

    
714
## License
715

    
716
[MIT](./LICENSE)
717

    
718
[npm]: https://img.shields.io/npm/v/terser-webpack-plugin.svg
719
[npm-url]: https://npmjs.com/package/terser-webpack-plugin
720
[node]: https://img.shields.io/node/v/terser-webpack-plugin.svg
721
[node-url]: https://nodejs.org
722
[deps]: https://david-dm.org/webpack-contrib/terser-webpack-plugin.svg
723
[deps-url]: https://david-dm.org/webpack-contrib/terser-webpack-plugin
724
[tests]: https://dev.azure.com/webpack-contrib/terser-webpack-plugin/_apis/build/status/webpack-contrib.terser-webpack-plugin?branchName=master
725
[tests-url]: https://dev.azure.com/webpack-contrib/terser-webpack-plugin/_build/latest?definitionId=7&branchName=master
726
[cover]: https://codecov.io/gh/webpack-contrib/terser-webpack-plugin/branch/master/graph/badge.svg
727
[cover-url]: https://codecov.io/gh/webpack-contrib/terser-webpack-plugin
728
[chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg
729
[chat-url]: https://gitter.im/webpack/webpack
730
[size]: https://packagephobia.now.sh/badge?p=terser-webpack-plugin
731
[size-url]: https://packagephobia.now.sh/result?p=terser-webpack-plugin
(3-3/4)