UNPKG

23.3 kBMarkdownView Raw
1<!--lint disable no-html-->
2
3<div align="center">
4 <a href="https://github.com/webpack/webpack">
5 <img width="200" height="200" hspace="10"
6 src="https://cdn.rawgit.com/webpack/media/e7485eb2/logo/icon.svg">
7 </a>
8 <h1>Imagemin Webpack</h1>
9 <p>
10 Plugin and Loader for <a href="http://webpack.js.org/">webpack</a> to optimize (compress) all images using <a href="https://github.com/imagemin/imagemin">imagemin</a>.
11 Do not worry about size of images, now they are always optimized/compressed.
12 </p>
13</div>
14
15<!--lint enable no-html-->
16
17[![npm][npm]][npm-url]
18[![node][node]][node-url]
19[![deps][deps]][deps-url]
20[![tests][tests]][tests-url]
21[![cover][cover]][cover-url]
22[![chat][chat]][chat-url]
23[![size][size]][size-url]
24
25# image-minimizer-webpack-plugin
26
27This plugin uses [imagemin](https://github.com/imagemin/imagemin) to optimize your images.
28
29## Getting Started
30
31To begin, you'll need to install `image-minimizer-webpack-plugin`:
32
33```console
34$ npm install image-minimizer-webpack-plugin --save-dev
35```
36
37Images can be optimized in two modes:
38
391. [Lossless](https://en.wikipedia.org/wiki/Lossless_compression) (without loss of quality).
402. [Lossy](https://en.wikipedia.org/wiki/Lossy_compression) (with loss of quality).
41
42Note:
43
44- [imagemin-mozjpeg](https://github.com/imagemin/imagemin-mozjpeg) can be configured in lossless and lossy mode.
45- [imagemin-svgo](https://github.com/imagemin/imagemin-svgo) can be configured in lossless and lossy mode.
46
47Explore the options to get the best result for you.
48
49**Recommended imagemin plugins for lossless optimization**
50
51```shell
52npm install imagemin-gifsicle imagemin-jpegtran imagemin-optipng imagemin-svgo --save-dev
53```
54
55**Recommended imagemin plugins for lossy optimization**
56
57```shell
58npm install imagemin-gifsicle imagemin-mozjpeg imagemin-pngquant imagemin-svgo --save-dev
59```
60
61**webpack.config.js**
62
63```js
64const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
65
66module.exports = {
67 module: {
68 rules: [
69 {
70 test: /\.(jpe?g|png|gif|svg)$/i,
71 use: [
72 {
73 loader: 'file-loader', // Or `url-loader` or your other loader
74 },
75 ],
76 },
77 ],
78 },
79 plugins: [
80 new ImageMinimizerPlugin({
81 minimizerOptions: {
82 // Lossless optimization with custom option
83 // Feel free to experiment with options for better result for you
84 plugins: [
85 ['gifsicle', { interlaced: true }],
86 ['jpegtran', { progressive: true }],
87 ['optipng', { optimizationLevel: 5 }],
88 [
89 'svgo',
90 {
91 plugins: [
92 {
93 removeViewBox: false,
94 },
95 ],
96 },
97 ],
98 ],
99 },
100 }),
101 ],
102};
103```
104
105> ℹ️ Only for `4` version of `webpack`: Make sure that plugin place after any plugins that add images or other assets which you want to optimized.\*\*
106
107> ℹ️ If you want to use `loader` or `plugin` standalone see sections below, but this is not recommended.
108
109### Standalone Loader
110
111[Documentation: Using loaders](https://webpack.js.org/concepts/loaders/)
112
113In your `webpack.config.js`, add the `ImageMinimizerPlugin.loader`, chained with the [file-loader](https://github.com/webpack/file-loader) or [url-loader](https://github.com/webpack-contrib/url-loader):
114
115**webpack.config.js**
116
117```js
118const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
119
120module.exports = {
121 module: {
122 rules: [
123 {
124 test: /\.(jpe?g|png|gif|svg)$/i,
125 use: [
126 {
127 loader: 'file-loader', // Or `url-loader` or your other loader
128 },
129 {
130 loader: ImageMinimizerPlugin.loader,
131 options: {
132 severityError: 'warning', // Ignore errors on corrupted images
133 minimizerOptions: {
134 plugins: ['gifsicle'],
135 },
136 },
137 },
138 ],
139 },
140 ],
141 },
142};
143```
144
145### Standalone Plugin
146
147[Documentation: Using plugins](https://webpack.js.org/concepts/plugins/)
148
149**webpack.config.js**
150
151```js
152const ImageminWebpack = require('image-minimizer-webpack-plugin');
153
154module.exports = {
155 module: {
156 rules: [
157 {
158 loader: 'file-loader',
159 options: {
160 name: '[path][name].[ext]',
161 },
162 test: /\.(jpe?g|png|gif|svg)$/i,
163 },
164 ],
165 },
166 plugins: [
167 // Make sure that the plugin placed after any plugins that added images
168 new ImageminWebpack({
169 severityError: 'warning', // Ignore errors on corrupted images
170 minimizerOptions: {
171 plugins: ['gifsicle'],
172 },
173 // Disable `loader`
174 loader: false,
175 }),
176 ],
177};
178```
179
180## Options
181
182### Plugin Options
183
184<!--lint disable no-html-->
185
186| Name | Type | Default | Description |
187| :------------------------: | :---------------------------------------: | :---------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------ |
188| **`test`** | `{String\/RegExp\|Array<String\|RegExp>}` | <code>/\.(jpe?g\|png\|gif\|tif\|webp\|svg\|avif)\$/i</code> | Test to match files against |
189| **`include`** | `{String\/RegExp\|Array<String\|RegExp>}` | `undefined` | Files to `include` |
190| **`exclude`** | `{String\/RegExp\|Array<String\|RegExp>}` | `undefined` | Files to `exclude` |
191| **`filter`** | `{Function}` | `() => true` | Allows filtering of images for optimization |
192| **`severityError`** | `{Boolean\|String}` | `'auto'` | Allows to choose how errors are displayed |
193| **`minimizerOptions`** | `{Object}` | `{ plugins: [] }` | Options for `imagemin` |
194| **`loader`** | `{Boolean}` | `true` | Automatically adding `imagemin-loader` (require for minification images using in `url-loader`, `svg-url-loader` or other) |
195| **`maxConcurrency`** | `{Number}` | `Math.max(1, os.cpus().length - 1)` | Maximum number of concurrency optimization processes in one time |
196| **`filename`** | `{string}` | `'[path][name][ext]'` | Allows to set the filename for the generated asset. Useful for converting to a `webp` |
197| **`deleteOriginalAssets`** | `{Boolean}` | `false` | Allows to delete the original asset. Useful for converting to a `webp` and remove original assets |
198
199<!--lint enable no-html-->
200
201#### `test`
202
203Type: `String|RegExp|Array<String|RegExp>`
204Default: `/\.(jpe?g\|png\|gif\|tif\|webp\|svg\|avif)\$/i`
205
206Test to match files against.
207
208**webpack.config.js**
209
210```js
211const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
212
213module.exports = {
214 plugins: [
215 new ImageMinimizerPlugin({
216 test: /\.(jpe?g|png|gif|svg)$/i,
217 }),
218 ],
219};
220```
221
222#### `include`
223
224Type: `String|RegExp|Array<String|RegExp>`
225Default: `undefined`
226
227Files to include.
228
229**webpack.config.js**
230
231```js
232const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
233
234module.exports = {
235 plugins: [
236 new ImageMinimizerPlugin({
237 include: /\/includes/,
238 }),
239 ],
240};
241```
242
243#### `exclude`
244
245Type: `String|RegExp|Array<String|RegExp>`
246Default: `undefined`
247
248Files to exclude.
249
250**webpack.config.js**
251
252```js
253const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
254
255module.exports = {
256 plugins: [
257 new ImageMinimizerPlugin({
258 exclude: /\/excludes/,
259 }),
260 ],
261};
262```
263
264#### `filter`
265
266Type: `Function`
267Default: `() => true`
268
269Allows filtering of images for optimization.
270
271Return `true` to optimize the image, `false` otherwise.
272
273**webpack.config.js**
274
275```js
276const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
277
278module.exports = {
279 plugins: [
280 new ImageMinimizerPlugin({
281 filter: (source, sourcePath) => {
282 // The `source` argument is a `Buffer` of source file
283 // The `sourcePath` argument is an absolute path to source
284 if (source.byteLength < 8192) {
285 return false;
286 }
287
288 return true;
289 },
290 }),
291 ],
292};
293```
294
295#### `severityError`
296
297Type: `Boolean|String`
298Default: `'auto'`
299
300Allows to choose how errors are displayed.
301
302Сan have the following values:
303
304- `'auto'` - emit warnings in `development` mode and emit errors in `production` mode (default behavior)
305- `false` or `'off'` - suppresses errors and warnings
306- `'warning'` - emit warnings instead errors
307- `true` or `'error'` - emit errors
308
309**webpack.config.js**
310
311```js
312const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
313
314module.exports = {
315 plugins: [
316 new ImageMinimizerPlugin({
317 severityError: 'warning',
318 }),
319 ],
320};
321```
322
323#### `minimizerOptions`
324
325Type: `Object`
326Default: `{ plugins: [] }`
327
328Options for [`imagemin`](https://github.com/imagemin/imagemin).
329
330More information and examples [here](https://github.com/imagemin/imagemin).
331
332**webpack.config.js**
333
334```js
335const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
336
337module.exports = {
338 plugins: [
339 new ImageMinimizerPlugin({
340 minimizerOptions: {
341 plugins: [
342 // Name
343 'gifsicle',
344 // Name with options
345 ['mozjpeg', { quality: 80 }],
346 // Full package name
347 [
348 'imagemin-svgo',
349 {
350 plugins: [
351 {
352 removeViewBox: false,
353 },
354 ],
355 },
356 ],
357 [
358 // Custom package name
359 'nonstandard-imagemin-package-name',
360 { myOptions: true },
361 ],
362 ],
363 },
364 }),
365 ],
366};
367```
368
369#### `loader`
370
371Type: `Boolean`
372Default: `true`
373
374Automatically adding `imagemin-loader`.
375
376**webpack.config.js**
377
378```js
379const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
380
381module.exports = {
382 plugins: [
383 new ImageMinimizerPlugin({
384 loader: false,
385 }),
386 ],
387};
388```
389
390#### `maxConcurrency`
391
392Type: `Number`
393Default: `Math.max(1, os.cpus().length - 1)`
394
395Maximum number of concurrency optimization processes in one time.
396
397**webpack.config.js**
398
399```js
400const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
401
402module.exports = {
403 plugins: [
404 new ImageMinimizerPlugin({
405 maxConcurrency: 3,
406 }),
407 ],
408};
409```
410
411#### `filename`
412
413Type: `String`
414Default: `'[path][name][ext]'`
415
416Allows to set the filename for the generated asset. Useful for converting to a `webp`.
417
418**webpack.config.js**
419
420```js
421const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
422
423module.exports = {
424 plugins: [
425 // Images are converted to `webp` and the original assets have been kept
426 new ImageMinimizerPlugin({
427 test: /\.(png)$/i,
428 filename: '[path][name].webp',
429 minimizerOptions: {
430 plugins: ['imagemin-webp'],
431 },
432 }),
433 ],
434};
435```
436
437#### `deleteOriginalAssets`
438
439Type: `Boolean`
440Default: `false`
441
442Allows to remove original assets. Useful for converting to a `webp` and remove original assets
443
444> i Doesn't make sense if you haven't changed the original value of the `filename` option
445
446**webpack.config.js**
447
448```js
449const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
450
451module.exports = {
452 plugins: [
453 // Images are converted to `webp` and the original assets have been removed
454 new ImageMinimizerPlugin({
455 test: /\.(png)$/i,
456 deleteOriginalAssets: true,
457 filename: '[path][name].webp',
458 minimizerOptions: {
459 plugins: ['imagemin-webp'],
460 },
461 }),
462 ],
463};
464```
465
466To generate and compress the original assets:
467
468```js
469const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
470
471module.exports = {
472 plugins: [
473 // And the original assets will be compressed
474 new ImageMinimizerPlugin({
475 test: /\.(png)$/i,
476 minimizerOptions: {
477 plugins: ['pngquant'],
478 },
479 }),
480 // Images are converted to `webp` and the original assets have been removed
481 new ImageMinimizerPlugin({
482 test: /\.(png)$/i,
483 deleteOriginalAssets: false,
484 filename: '[path][name].webp',
485 minimizerOptions: {
486 plugins: ['imagemin-webp'],
487 },
488 }),
489 ],
490};
491```
492
493### Loader Options
494
495| Name | Type | Default | Description |
496| :------------------------: | :-----------------: | :-------------------: | :------------------------------------------------------------------------------------------------ |
497| **`filter`** | `{Function}` | `undefined` | Allows filtering of images for optimization |
498| **`severityError`** | `{Boolean\|String}` | `'auto'` | Allows to choose how errors are displayed |
499| **`minimizerOptions`** | `{Object}` | `{ plugins: [] }` | Options for `imagemin` |
500| **`filename`** | `{string}` | `'[path][name][ext]'` | Allows to set the filename for the generated asset. Useful for converting to a `webp` |
501| **`deleteOriginalAssets`** | `{Boolean}` | `false` | Allows to delete the original asset. Useful for converting to a `webp` and remove original assets |
502
503#### `filter`
504
505Type: `Function`
506Default: `() => true`
507
508Allows filtering of images for optimization.
509
510Return `true` to optimize the image, `false` otherwise.
511
512**webpack.config.js**
513
514```js
515const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
516
517module.exports = {
518 module: {
519 rules: [
520 {
521 test: /\.(jpe?g|png|gif|svg)$/i,
522 use: [
523 {
524 loader: 'file-loader', // Or `url-loader` or your other loader
525 },
526 {
527 loader: ImageMinimizerPlugin.loader,
528 options: {
529 cache: true,
530 filter: (source, sourcePath) => {
531 // The `source` argument is a `Buffer` of source file
532 // The `sourcePath` argument is an absolute path to source
533 if (source.byteLength < 8192) {
534 return false;
535 }
536
537 return true;
538 },
539 minimizerOptions: {
540 plugins: ['gifsicle'],
541 },
542 },
543 },
544 ],
545 },
546 ],
547 },
548};
549```
550
551#### `severityError`
552
553Type: `Boolean|String`
554Default: `'auto'`
555
556Allows to choose how errors are displayed.
557
558Сan have the following values:
559
560- `'auto'` - emit warnings in `development` mode and emit errors in `production` mode (default behavior)
561- `false` or `'off'` - suppresses errors and warnings
562- `'warning'` - emit warnings instead errors
563- `true` or `'error'` - emit errors
564
565**webpack.config.js**
566
567```js
568const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
569
570module.exports = {
571 module: {
572 rules: [
573 {
574 test: /\.(jpe?g|png|gif|svg)$/i,
575 use: [
576 {
577 loader: 'file-loader', // Or `url-loader` or your other loader
578 },
579 {
580 loader: ImageMinimizerPlugin.loader,
581 options: {
582 severityError: 'warning',
583 minimizerOptions: {
584 plugins: ['gifsicle'],
585 },
586 },
587 },
588 ],
589 },
590 ],
591 },
592};
593```
594
595#### `minimizerOptions`
596
597Type: `Object`
598Default: `{ plugins: [] }`
599
600Options for `imagemin`.
601
602Options for [`imagemin`](https://github.com/imagemin/imagemin)
603
604**webpack.config.js**
605
606```js
607const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
608
609module.exports = {
610 module: {
611 rules: [
612 {
613 test: /\.(jpe?g|png|gif|svg)$/i,
614 use: [
615 {
616 loader: 'file-loader', // Or `url-loader` or your other loader
617 },
618 {
619 loader: ImageMinimizerPlugin.loader,
620 options: {
621 severityError: 'warning',
622 minimizerOptions: {
623 plugins: [
624 ['gifsicle', { interlaced: true, optimizationLevel: 3 }],
625 ],
626 },
627 },
628 },
629 ],
630 },
631 ],
632 },
633};
634```
635
636#### `filename`
637
638Type: `String`
639Default: `'[path][name][ext]'`
640
641Allows to set the filename for the generated asset. Useful for converting to a `webp`.
642
643**webpack.config.js**
644
645```js
646const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
647
648module.exports = {
649 module: {
650 rules: [
651 {
652 test: /\.(jpe?g|png|gif)$/i,
653 use: [
654 {
655 loader: 'file-loader', // Or `url-loader` or your other loader
656 },
657 {
658 loader: ImageMinimizerPlugin.loader,
659 options: {
660 filename: '[path][name].webp',
661 minimizerOptions: {
662 plugins: ['imagemin-webp'],
663 },
664 },
665 },
666 ],
667 },
668 ],
669 },
670};
671```
672
673#### `deleteOriginalAssets`
674
675Type: `Boolean`
676Default: `false`
677
678Allows to keep the original asset. Useful for converting to a `webp` and remove original assets.
679
680> i Doesn't make sense if you haven't changed the original value of the `filename` option
681
682**webpack.config.js**
683
684```js
685const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
686
687module.exports = {
688 module: {
689 rules: [
690 {
691 test: /\.(png)$/i,
692 use: [
693 {
694 loader: 'file-loader', // Or `url-loader` or your other loader
695 },
696 {
697 loader: ImageMinimizerPlugin.loader,
698 options: {
699 // PNG images are converted to WEBP, and the originals will keep
700 deleteOriginalAssets: false,
701 filename: '[path][name].webp',
702 minimizerOptions: {
703 plugins: ['imagemin-webp'],
704 },
705 },
706 },
707 ],
708 },
709 ],
710 },
711};
712```
713
714## Additional API
715
716### `normalizeConfig(config)`
717
718The function normalizes configuration (converts plugins names and options to `Function`s) for using in `imagemin` package directly.
719
720```js
721const imagemin = require('imagemin');
722const { normalizeConfig } = require('image-minimizer-webpack-plugin');
723const imageminConfig = normalizeConfig({
724 plugins: [
725 'jpegtran',
726 [
727 'pngquant',
728 {
729 quality: [0.6, 0.8],
730 },
731 ],
732 ],
733});
734
735/*
736 console.log(imageminConfig);
737 =>
738 {
739 plugins: [Function, Function],
740 pluginsMeta: [
741 { name: "imagemin-jpegtran", version: "x.x.x", options: {} },
742 { name: "imagemin-pngquant", version: "x.x.x", options: { quality: [0.6, 0.8] }
743 ]
744 }
745*/
746
747(async () => {
748 const files = await imagemin(['images/*.{jpg,png}'], {
749 destination: 'build/images',
750 plugins: imageminConfig.plugins,
751 });
752
753 console.log(files);
754 // => [{data: <Buffer 89 50 4e …>, path: 'build/images/foo.jpg'}, …]
755})();
756```
757
758## Examples
759
760### Optimize images based on size
761
762You can use difference options (like `progressive`/`interlaced` and etc) based on image size (example - don't do progressive transformation for small images).
763
764What is `progressive` image? [`Answer here`](https://jmperezperez.com/medium-image-progressive-loading-placeholder/).
765
766**webpack.config.js**
767
768```js
769const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
770
771module.exports = {
772 minimizer: [
773 new ImageMinimizerPlugin({
774 // Only apply this one to files equal to or over 8192 bytes
775 filter: (source) => {
776 if (source.byteLength >= 8192) {
777 return true;
778 }
779
780 return false;
781 },
782 minimizerOptions: {
783 plugins: [['jpegtran', { progressive: true }]],
784 },
785 }),
786 new ImageMinimizerPlugin({
787 // Only apply this one to files under 8192
788 filter: (source) => {
789 if (source.byteLength < 8192) {
790 return true;
791 }
792
793 return false;
794 },
795 minimizerOptions: {
796 plugins: [['jpegtran', { progressive: false }]],
797 },
798 }),
799 ],
800};
801```
802
803### Optimize and transform images to `webp`
804
805```js
806const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
807
808module.exports = {
809 plugins: [
810 new ImageMinimizerPlugin({
811 minimizerOptions: {
812 plugins: ['pngquant'],
813 },
814 }),
815 new ImageMinimizerPlugin({
816 deleteOriginalAssets: false,
817 filename: '[path][name].webp',
818 minimizerOptions: {
819 plugins: ['imagemin-webp'],
820 },
821 }),
822 ],
823};
824```
825
826## Contributing
827
828Please take a moment to read our contributing guidelines if you haven't yet done so.
829
830[CONTRIBUTING](./.github/CONTRIBUTING.md)
831
832## License
833
834[MIT](./LICENSE)
835
836[npm]: https://img.shields.io/npm/v/image-minimizer-webpack-plugin.svg
837[npm-url]: https://npmjs.com/package/image-minimizer-webpack-plugin
838[node]: https://img.shields.io/node/v/image-minimizer-webpack-plugin.svg
839[node-url]: https://nodejs.org
840[deps]: https://david-dm.org/webpack-contrib/image-minimizer-webpack-plugin.svg
841[deps-url]: https://david-dm.org/webpack-contrib/image-minimizer-webpack-plugin
842[tests]: https://github.com/webpack-contrib/image-minimizer-webpack-plugin/workflows/image-minimizer-webpack-plugin/badge.svg
843[tests-url]: https://github.com/webpack-contrib/image-minimizer-webpack-plugin/actions
844[cover]: https://codecov.io/gh/webpack-contrib/image-minimizer-webpack-plugin/branch/master/graph/badge.svg
845[cover-url]: https://codecov.io/gh/webpack-contrib/image-minimizer-webpack-plugin
846[chat]: https://badges.gitter.im/webpack/webpack.svg
847[chat-url]: https://gitter.im/webpack/webpack
848[size]: https://packagephobia.now.sh/badge?p=image-minimizer-webpack-plugin
849[size-url]: https://packagephobia.now.sh/result?p=image-minimizer-webpack-plugin