UNPKG

44.8 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
27## Getting Started
28
29This plugin can use 2 tools to optimize/generate images:
30
31- [`imagemin`](https://github.com/imagemin/imagemin) - optimize your images by default, since it is stable and works with all types of images
32- [`squoosh`](https://github.com/GoogleChromeLabs/squoosh/tree/dev/libsquoosh) - while working in experimental mode with `.jpg`, `.jpeg`, `.png`, `.webp`, `.avif` file types.
33
34> ⚠️ By default we don't install anything
35
36To begin, you'll need to install `image-minimizer-webpack-plugin` and image minimizer/generator:
37
38- [imagemin](https://github.com/imagemin/imagemin):
39
40```console
41$ npm install image-minimizer-webpack-plugin imagemin --save-dev
42```
43
44> ⚠️ imagemin uses plugin to optimize/generate images, so you need to isntall them too
45
46- [`squoosh`](https://github.com/GoogleChromeLabs/squoosh/tree/dev/libsquoosh):
47
48```console
49$ npm install image-minimizer-webpack-plugin @squoosh/lib --save-dev
50```
51
52Images can be optimized in two modes:
53
541. [Lossless](https://en.wikipedia.org/wiki/Lossless_compression) (without loss of quality).
552. [Lossy](https://en.wikipedia.org/wiki/Lossy_compression) (with loss of quality).
56
57### Optimize with [imagemin](https://github.com/imagemin/imagemin)
58
59Note:
60
61- [imagemin-mozjpeg](https://github.com/imagemin/imagemin-mozjpeg) can be configured in lossless and lossy mode.
62- [imagemin-svgo](https://github.com/imagemin/imagemin-svgo) can be configured in lossless and lossy mode.
63
64Explore the options to get the best result for you.
65
66**Recommended imagemin plugins for lossless optimization**
67
68```shell
69npm install imagemin-gifsicle imagemin-jpegtran imagemin-optipng imagemin-svgo --save-dev
70```
71
72**Recommended imagemin plugins for lossy optimization**
73
74```shell
75npm install imagemin-gifsicle imagemin-mozjpeg imagemin-pngquant imagemin-svgo --save-dev
76```
77
78For `imagemin-svgo` v9.0.0+ need use svgo [configuration](https://github.com/svg/svgo#configuration)
79
80**webpack.config.js**
81
82```js
83const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
84const { extendDefaultPlugins } = require("svgo");
85
86module.exports = {
87 module: {
88 rules: [
89 {
90 test: /\.(jpe?g|png|gif|svg)$/i,
91 type: "asset",
92 },
93 ],
94 },
95 optimization: {
96 minimizer: [
97 "...",
98 new ImageMinimizerPlugin({
99 minimizer: {
100 implementation: ImageMinimizerPlugin.imageminMinify,
101 options: {
102 // Lossless optimization with custom option
103 // Feel free to experiment with options for better result for you
104 plugins: [
105 ["gifsicle", { interlaced: true }],
106 ["jpegtran", { progressive: true }],
107 ["optipng", { optimizationLevel: 5 }],
108 // Svgo configuration here https://github.com/svg/svgo#configuration
109 [
110 "svgo",
111 {
112 plugins: extendDefaultPlugins([
113 {
114 name: "removeViewBox",
115 active: false,
116 },
117 {
118 name: "addAttributesToSVGElement",
119 params: {
120 attributes: [{ xmlns: "http://www.w3.org/2000/svg" }],
121 },
122 },
123 ]),
124 },
125 ],
126 ],
127 },
128 },
129 }),
130 ],
131 },
132};
133```
134
135### Optimize with [`squoosh`](https://github.com/GoogleChromeLabs/squoosh/tree/dev/libsquoosh)
136
137```console
138$ npm install @squoosh/lib --save-dev
139```
140
141**Recommended `@squoosh/lib` options for lossy optimization**
142
143For lossy optimization we recommend using the default settings of `@squoosh/lib` package.
144The default values and supported file types for each option can be found in the [codecs.ts](https://github.com/GoogleChromeLabs/squoosh/blob/dev/libsquoosh/src/codecs.ts) file under codecs.
145
146**webpack.config.js**
147
148```js
149const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
150
151module.exports = {
152 module: {
153 rules: [
154 // You need this, if you are using `import file from "file.ext"`, for `new URL(...)` syntax you don't need it
155 {
156 test: /\.(jpe?g|png)$/i,
157 type: "asset",
158 },
159 ],
160 },
161 optimization: {
162 minimizer: [
163 "...",
164 new ImageMinimizerPlugin({
165 minimizer: {
166 implementation: ImageMinimizerPlugin.squooshMinify,
167 options: {
168 // Your options for `squoosh`
169 },
170 },
171 }),
172 ],
173 },
174};
175```
176
177**Recommended `squoosh` options for lossless optimization**
178
179For lossless optimization we recommend using the options listed below in `minimizer.options.encodeOptions`.
180
181**webpack.config.js**
182
183```js
184const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
185
186module.exports = {
187 module: {
188 rules: [
189 // You need this, if you are using `import file from "file.ext"`, for `new URL(...)` syntax you don't need it
190 {
191 test: /\.(jpe?g|png)$/i,
192 type: "asset",
193 },
194 ],
195 },
196 optimization: {
197 minimizer: [
198 new ImageMinimizerPlugin({
199 minimizer: {
200 implementation: ImageMinimizerPlugin.squooshMinify,
201 options: {
202 encodeOptions: {
203 mozjpeg: {
204 // That setting might be close to lossless, but it’s not guaranteed
205 // https://github.com/GoogleChromeLabs/squoosh/issues/85
206 quality: 100,
207 },
208 webp: {
209 lossless: 1,
210 },
211 avif: {
212 // https://github.com/GoogleChromeLabs/squoosh/blob/dev/codecs/avif/enc/README.md
213 cqLevel: 0,
214 },
215 },
216 },
217 },
218 }),
219 ],
220 },
221};
222```
223
224### Advanced setup
225
226If you want to use `loader` or `plugin` standalone see sections below, but this is **not recommended**.
227
228By default, plugin configures `loader` (please use the `loader` option if you want to disable this behaviour), therefore you should not setup standalone loader when you use a plugin setup.
229
230Loader optimizes or generates images using options, so inlined images via `data` URI (i.e. `data:`) will be optimized or generated too, not inlined images will be optimized too.
231
232#### Standalone Loader
233
234[Documentation: Using loaders](https://webpack.js.org/concepts/loaders/).
235
236In your `webpack.config.js`, add the `ImageMinimizerPlugin.loader` and specify the [asset modules options](https://webpack.js.org/guides/asset-modules/) (if you use images in `import`):
237
238**webpack.config.js**
239
240```js
241const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
242
243module.exports = {
244 module: {
245 rules: [
246 // You need this, if you are using `import file from "file.ext"`, for `new URL(...)` syntax you don't need it
247 {
248 test: /\.(jpe?g|png|gif|svg)$/i,
249 type: "asset",
250 },
251 // We recommend using only for the "production" mode
252 {
253 test: /\.(jpe?g|png|gif|svg)$/i,
254 use: [
255 {
256 loader: ImageMinimizerPlugin.loader,
257 enforce: "pre",
258 options: {
259 minimizer: {
260 implementation: ImageMinimizerPlugin.imageminMinify,
261 options: {
262 plugins: [
263 "imagemin-gifsicle",
264 "imagemin-mozjpeg",
265 "imagemin-pngquant",
266 "imagemin-svgo",
267 ],
268 },
269 },
270 },
271 },
272 ],
273 },
274 ],
275 },
276};
277```
278
279### Standalone Plugin
280
281[Documentation: Using plugins](https://webpack.js.org/concepts/plugins/).
282
283**webpack.config.js**
284
285```js
286const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
287
288module.exports = {
289 module: {
290 rules: [
291 // You need this, if you are using `import file from "file.ext"`, for `new URL(...)` syntax you don't need it
292 {
293 test: /\.(jpe?g|png|gif|svg)$/i,
294 type: "asset",
295 },
296 ],
297 },
298 optimization: {
299 minimizer: [
300 // Extend default minimizer, i.e. `terser-webpack-plugin` for JS
301 "...",
302 // We recommend using only for the "production" mode
303 new ImageMinimizerPlugin({
304 minimizer: {
305 implementation: ImageMinimizerPlugin.imageminMinify,
306 options: {
307 plugins: [
308 "imagemin-gifsicle",
309 "imagemin-mozjpeg",
310 "imagemin-pngquant",
311 "imagemin-svgo",
312 ],
313 },
314 },
315 // Disable `loader`
316 loader: false,
317 }),
318 ],
319 },
320};
321```
322
323## Options
324
325### Plugin Options
326
327| Name | Type | Default | Description |
328| :-------------------------------------------------: | :---------------------------------------: | :---------------------------------------------------------: | :--------------------------------------------------------------- |
329| **[`test`](#test)** | `{String\/RegExp\|Array<String\|RegExp>}` | <code>/\.(jpe?g\|png\|gif\|tif\|webp\|svg\|avif)\$/i</code> | Test to match files against |
330| **[`include`](#include)** | `{String\/RegExp\|Array<String\|RegExp>}` | `undefined` | Files to include |
331| **[`exclude`](#exclude)** | `{String\/RegExp\|Array<String\|RegExp>}` | `undefined` | Files to exclude |
332| **[`minimizer`](#minimizer)** | `{Object \| Array<Object>}` | `undefined` | Allows to setup default minimizer |
333| **[`generator`](#generator)** | `{Array<Object>}` | `undefined` | Allow to setup default generators |
334| **[`severityError`](#severityerror)** | `{String}` | `'error'` | Allows to choose how errors are displayed |
335| **[`loader`](#loader)** | `{Boolean}` | `true` | Automatically adding built-in loader |
336| **[`concurrency`](#concurrency)** | `{Number}` | `Math.max(1, os.cpus().length - 1)` | Maximum number of concurrency optimization processes in one time |
337| **[`deleteOriginalAssets`](#deleteoriginalassets)** | `{Boolean}` | `true` | Allows to delete the original asset for minimizer |
338
339#### `test`
340
341Type: `String|RegExp|Array<String|RegExp>`
342Default: `/\.(jpe?g\|png\|gif\|tif\|webp\|svg\|avif)\$/i`
343
344Test to match files against.
345
346**webpack.config.js**
347
348```js
349const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
350
351module.exports = {
352 optimization: {
353 minimizer: [
354 "...",
355 new ImageMinimizerPlugin({
356 test: /\.(jpe?g|png|gif|svg)$/i,
357 }),
358 ],
359 },
360};
361```
362
363#### `include`
364
365Type: `String|RegExp|Array<String|RegExp>`
366Default: `undefined`
367
368Files to include.
369
370**webpack.config.js**
371
372```js
373const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
374
375module.exports = {
376 optimization: {
377 minimizer: [
378 "...",
379 new ImageMinimizerPlugin({
380 include: /\/includes/,
381 }),
382 ],
383 },
384};
385```
386
387#### `exclude`
388
389Type: `String|RegExp|Array<String|RegExp>`
390Default: `undefined`
391
392Files to exclude.
393
394**webpack.config.js**
395
396```js
397const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
398
399module.exports = {
400 optimization: {
401 minimizer: [
402 "...",
403 new ImageMinimizerPlugin({
404 exclude: /\/excludes/,
405 }),
406 ],
407 },
408};
409```
410
411#### `minimizer`
412
413Type: `Object|Array<Object>`
414Default: `undefined`
415
416Allows to setup default minify function.
417
418Available minimizers:
419
420- `ImageMinimizerPlugin.imageminMinify`
421- `ImageMinimizerPlugin.squooshMinify`
422
423##### `Object`
424
425For imagemin:
426
427**webpack.config.js**
428
429```js
430const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
431
432module.exports = {
433 optimization: {
434 minimizer: [
435 "...",
436 new ImageMinimizerPlugin({
437 minimizer: {
438 // Implementation
439 implementation: ImageMinimizerPlugin.imageminMinify,
440 // Options
441 options: {
442 plugins: [
443 "imagemin-gifsicle",
444 "imagemin-mozjpeg",
445 "imagemin-pngquant",
446 "imagemin-svgo",
447 ],
448 },
449 },
450 }),
451 ],
452 },
453};
454```
455
456More information and examples [here](https://github.com/imagemin/imagemin).
457
458For squoosh:
459
460**webpack.config.js**
461
462```js
463const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
464
465module.exports = {
466 optimization: {
467 minimizer: [
468 "...",
469 new ImageMinimizerPlugin({
470 minimizer: {
471 // Implementation
472 implementation: ImageMinimizerPlugin.squooshMinify,
473 // Options
474 options: {
475 encodeOptions: {
476 mozjpeg: {
477 quality: 90,
478 },
479 },
480 },
481 },
482 }),
483 ],
484 },
485};
486```
487
488More information and examples [here](https://github.com/GoogleChromeLabs/squoosh/tree/dev/libsquoosh).
489
490Minimizer option list:
491
492###### `implementation`
493
494Type: `Function`
495Default: `undefined`
496
497Configure the default `implementation`.
498
499**webpack.config.js**
500
501```js
502const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
503
504module.exports = {
505 optimization: {
506 minimizer: [
507 "...",
508 new ImageMinimizerPlugin({
509 minimizer: {
510 // Implementation
511 implementation: ImageMinimizerPlugin.squooshMinify,
512 },
513 }),
514 ],
515 },
516};
517```
518
519###### `options`
520
521Type: `Object`
522Default: `undefined`
523
524Options for the `implementation` option (i.e. options for `imagemin`/`squoosh`/custom implementation).
525
526**webpack.config.js**
527
528```js
529const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
530
531module.exports = {
532 optimization: {
533 minimizer: [
534 "...",
535 new ImageMinimizerPlugin({
536 minimizer: {
537 implementation: ImageMinimizerPlugin.squooshMinify,
538 // Options
539 options: {
540 encodeOptions: {
541 mozjpeg: {
542 quality: 90,
543 },
544 },
545 },
546 },
547 }),
548 ],
549 },
550};
551```
552
553###### `filter`
554
555Type: `Function`
556Default: `() => true`
557
558Allows filtering of images for optimization/generation.
559
560Return `true` to optimize the image, `false` otherwise.
561
562**webpack.config.js**
563
564```js
565const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
566
567module.exports = {
568 optimization: {
569 minimizer: [
570 "...",
571 new ImageMinimizerPlugin({
572 minimizer: {
573 filter: (source, sourcePath) => {
574 // The `source` argument is a `Buffer` of source file
575 // The `sourcePath` argument is an absolute path to source
576 if (source.byteLength < 8192) {
577 return false;
578 }
579
580 return true;
581 },
582 implementation: ImageMinimizerPlugin.imageminMinify,
583 options: {
584 plugins: [
585 "imagemin-gifsicle",
586 "imagemin-mozjpeg",
587 "imagemin-pngquant",
588 "imagemin-svgo",
589 ],
590 },
591 },
592 }),
593 ],
594 },
595};
596```
597
598###### `filename`
599
600Type: `string | Function`
601Default: `undefined`
602
603Allows to set the filename.
604Supported values see in [`webpack template strings`](https://webpack.js.org/configuration/output/#template-strings), `File-level` section.
605
606**webpack.config.js**
607
608```js
609const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
610
611module.exports = {
612 optimization: {
613 minimizer: [
614 "...",
615 new ImageMinimizerPlugin({
616 minimizer: {
617 filename: "optimized-[name][ext]",
618 implementation: ImageMinimizerPlugin.squooshMinify,
619 // Options
620 options: {
621 encodeOptions: {
622 mozjpeg: {
623 quality: 90,
624 },
625 },
626 },
627 },
628 }),
629 ],
630 },
631};
632```
633
634Example `Function` usage:
635
636**webpack.config.js**
637
638```js
639const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
640
641module.exports = {
642 optimization: {
643 minimizer: [
644 "...",
645 new ImageMinimizerPlugin({
646 minimizer: {
647 filename: () => "optimized-[name][ext]",
648 implementation: ImageMinimizerPlugin.squooshMinify,
649 // Options
650 options: {
651 encodeOptions: {
652 mozjpeg: {
653 quality: 90,
654 },
655 },
656 },
657 },
658 }),
659 ],
660 },
661};
662```
663
664##### `Array`
665
666Allows to setup multiple minimizers.
667
668**webpack.config.js**
669
670```js
671const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
672
673module.exports = {
674 optimization: {
675 minimizer: [
676 "...",
677 new ImageMinimizerPlugin({
678 minimizer: [
679 {
680 implementation: ImageMinimizerPlugin.imageminMinify,
681 options: {
682 plugins: [
683 "imagemin-gifsicle",
684 "imagemin-mozjpeg",
685 "imagemin-pngquant",
686 "imagemin-svgo",
687 ],
688 },
689 },
690 {
691 implementation: (original, options) => {
692 let result;
693
694 try {
695 result = minifyAndReturnBuffer(original.data);
696 } catch (error) {
697 // Return original input if there was an error
698 return {
699 filename: original.filename,
700 data: original.data,
701 errors: [error],
702 warnings: [],
703 };
704 }
705
706 return {
707 filename: original.filename,
708 data: result,
709 warnings: [],
710 errors: [],
711 info: {
712 // Please always set it to prevent double minification
713 minimized: true,
714 // Optional
715 minimizedBy: ["custom-name-of-minimication"],
716 },
717 };
718 },
719 options: {
720 // Custom options
721 },
722 },
723 ],
724 }),
725 ],
726 },
727};
728```
729
730#### `generator`
731
732Type: `Array<Object>`
733Default: `undefined`
734
735Allow to setup default generators.
736Useful if you need generate `webp`/`avif`/etc from other formats.
737
738> ⚠️ If no generator was found for the image (i.e. no `?as=webp` was found in query params), the `minimizer` option will be used. Therefore, it is recommended to configure generator outputs optimized image.
739> ⚠️ The option will not work if you disable `loader` (i.e. set the `loader` option to `false`).
740
741Available generators:
742
743- `ImageMinimizerPlugin.imageminGenerate`
744- `ImageMinimizerPlugin.squooshGenerate`
745
746Example `webp` generator:
747
748- imagemin
749
750**webpack.config.js**
751
752```js
753const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
754
755module.exports = {
756 optimization: {
757 minimizer: [
758 "...",
759 new ImageMinimizerPlugin({
760 generator: [
761 {
762 // You can apply generator using `?as=webp`, you can use any name and provide more options
763 preset: "webp",
764 implementation: ImageMinimizerPlugin.imageminGenerate,
765 options: {
766 // Please specify only one plugin here, multiple plugins will not work
767 plugins: ["imagemin-webp"],
768 },
769 },
770 ],
771 }),
772 ],
773 },
774};
775```
776
777- squoosh
778
779**webpack.config.js**
780
781```js
782const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
783
784module.exports = {
785 optimization: {
786 minimizer: [
787 "...",
788 new ImageMinimizerPlugin({
789 generator: [
790 {
791 // You can apply generator using `?as=webp`, you can use any name and provide more options
792 preset: "webp",
793 implementation: ImageMinimizerPlugin.squooshGenerate,
794 options: {
795 encodeOptions: {
796 // Please specify only one codec here, multiple codecs will not work
797 webp: {
798 quality: 90,
799 },
800 },
801 },
802 },
803 ],
804 }),
805 ],
806 },
807};
808```
809
810Now you can generate the new image using:
811
812```js
813// Old approach for getting URL
814import webp from "./file.jpg?as=webp";
815
816// Assets modules
817console.log(new URL("./file.jpg?as=webp"));
818```
819
820```css
821div {
822 background: url("./file.jpg?as=webp");
823}
824```
825
826You can use `?as=webp` in any type of files.
827
828Example multiple generators:
829
830**webpack.config.js**
831
832```js
833const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
834
835module.exports = {
836 optimization: {
837 minimizer: [
838 "...",
839 new ImageMinimizerPlugin({
840 generator: [
841 {
842 // You can apply generator using `?as=webp`, you can use any name and provide more options
843 preset: "webp",
844 implementation: ImageMinimizerPlugin.squooshGenerate,
845 options: {
846 encodeOptions: {
847 webp: {
848 quality: 90,
849 },
850 },
851 },
852 },
853 {
854 // You can apply generator using `?as=avif`, you can use any name and provide more options
855 preset: "avif",
856 implementation: ImageMinimizerPlugin.squooshGenerate,
857 options: {
858 encodeOptions: {
859 avif: {
860 cqLevel: 33,
861 },
862 },
863 },
864 },
865 ],
866 }),
867 ],
868 },
869};
870```
871
872`squoosh` generator supports more options, for example you can resize an image:
873
874**webpack.config.js**
875
876```js
877const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
878
879module.exports = {
880 optimization: {
881 minimizer: [
882 "...",
883 new ImageMinimizerPlugin({
884 generator: [
885 {
886 // You can apply generator using `?as=webp-100-50`, you can use any name and provide more options
887 preset: "webp-100-50",
888 implementation: ImageMinimizerPlugin.squooshGenerate,
889 options: {
890 encodeOptions: {
891 resize: {
892 enabled: true,
893 width: 100,
894 height: 50,
895 },
896 webp: {
897 quality: 90,
898 },
899 },
900 },
901 },
902 ],
903 }),
904 ],
905 },
906};
907```
908
909You can find more information [here](https://github.com/GoogleChromeLabs/squoosh/tree/dev/libsquoosh).
910
911You can use your own generator implementation.
912
913**webpack.config.js**
914
915```js
916const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
917
918module.exports = {
919 optimization: {
920 minimizer: [
921 "...",
922 new ImageMinimizerPlugin({
923 generator: [
924 {
925 // You can apply generator using `?as=webp`, you can use any name and provide more options
926 preset: "webp",
927 implementation: (original, options) => {
928 let result;
929
930 try {
931 result = minifyAndReturnBuffer(original.data);
932 } catch (error) {
933 // Return original input if there was an error
934 return {
935 filename: original.filename,
936 data: original.data,
937 errors: [error],
938 warnings: [],
939 };
940 }
941
942 return {
943 filename: original.filename,
944 data: result,
945 warnings: [],
946 errors: [],
947 info: {
948 // Please always set it to prevent double minification
949 generated: true,
950 // Optional
951 generatedBy: ["custom-name-of-minimication"],
952 },
953 };
954 },
955 options: {
956 // Your options
957 },
958 },
959 ],
960 }),
961 ],
962 },
963};
964```
965
966Generator option list:
967
968###### `type`
969
970Type: `"import" | "asset"`
971Default: `"import"`
972
973Allows you to apply the generator for `import` or assets from compilation (useful for copied assets).
974By default, generators are applying on `import`/`require`, but sometimes you need to generate new images from other plugins (for example - `copy-webpack-plugin`), if you need this, please set `asset` value for the `type` option.
975
976**webpack.config.js**
977
978```js
979const CopyPlugin = require("copy-webpack-plugin");
980const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
981
982module.exports = {
983 optimization: {
984 minimizer: [
985 "...",
986 new ImageMinimizerPlugin({
987 minimizer: {
988 implementation: ImageMinimizerPlugin.imageminMinify,
989 options: {
990 plugins: [
991 "imagemin-gifsicle",
992 "imagemin-mozjpeg",
993 "imagemin-pngquant",
994 "imagemin-svgo",
995 ],
996 },
997 },
998 generator: [
999 {
1000 // Apply generator for copied assets
1001 type: "asset",
1002 // You can use `ImageMinimizerPlugin.squooshGenerate`
1003 implementation: ImageMinimizerPlugin.imageminGenerate,
1004 options: {
1005 plugins: ["imagemin-webp"],
1006 },
1007 },
1008 ],
1009 }),
1010 ],
1011 },
1012 plugnins: [new CopyPlugin({ patterns: ["images/**/*.png"] })],
1013};
1014```
1015
1016###### `preset`
1017
1018Type: `String`
1019Default: `undefined`
1020
1021Configure the name of preset, i.e. you can use it in `?as=name`.
1022
1023**webpack.config.js**
1024
1025```js
1026const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1027
1028module.exports = {
1029 optimization: {
1030 minimizer: [
1031 "...",
1032 new ImageMinimizerPlugin({
1033 generator: [
1034 {
1035 preset: "name",
1036 // Implementation
1037 implementation: ImageMinimizerPlugin.squooshMinify,
1038 },
1039 ],
1040 }),
1041 ],
1042 },
1043};
1044```
1045
1046###### `implementation`
1047
1048Type: `Function`
1049Default: `undefined`
1050
1051Configure the default `implementation`.
1052
1053**webpack.config.js**
1054
1055```js
1056const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1057
1058module.exports = {
1059 optimization: {
1060 minimizer: [
1061 "...",
1062 new ImageMinimizerPlugin({
1063 generator: [
1064 {
1065 preset: "name",
1066 // Implementation
1067 implementation: ImageMinimizerPlugin.squooshMinify,
1068 },
1069 ],
1070 }),
1071 ],
1072 },
1073};
1074```
1075
1076###### `options`
1077
1078Type: `Object`
1079Default: `undefined`
1080
1081Options for the `implementation` option (i.e. options for `imagemin`/`squoosh`/custom implementation).
1082
1083**webpack.config.js**
1084
1085```js
1086const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1087
1088module.exports = {
1089 optimization: {
1090 minimizer: [
1091 "...",
1092 new ImageMinimizerPlugin({
1093 generator: [
1094 {
1095 preset: "name",
1096 implementation: ImageMinimizerPlugin.squooshMinify,
1097 // Options
1098 options: {
1099 encodeOptions: {
1100 mozjpeg: {
1101 quality: 90,
1102 },
1103 },
1104 },
1105 },
1106 ],
1107 }),
1108 ],
1109 },
1110};
1111```
1112
1113###### `filter`
1114
1115Type: `Function`
1116Default: `() => true`
1117
1118Allows filtering of images for optimization/generation.
1119
1120Return `true` to optimize the image, `false` otherwise.
1121
1122**webpack.config.js**
1123
1124```js
1125const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1126
1127module.exports = {
1128 optimization: {
1129 minimizer: [
1130 "...",
1131 new ImageMinimizerPlugin({
1132 generator: [
1133 {
1134 preset: "name",
1135 filter: (source, sourcePath) => {
1136 // The `source` argument is a `Buffer` of source file
1137 // The `sourcePath` argument is an absolute path to source
1138 if (source.byteLength < 8192) {
1139 return false;
1140 }
1141
1142 return true;
1143 },
1144 implementation: ImageMinimizerPlugin.imageminMinify,
1145 options: {
1146 plugins: [
1147 "imagemin-gifsicle",
1148 "imagemin-mozjpeg",
1149 "imagemin-pngquant",
1150 "imagemin-svgo",
1151 ],
1152 },
1153 },
1154 ],
1155 }),
1156 ],
1157 },
1158};
1159```
1160
1161###### `filename`
1162
1163Type: `string | Function`
1164Default: `undefined`
1165
1166Allows to set the filename.
1167Supported values see in [`webpack template strings`](https://webpack.js.org/configuration/output/#template-strings), `File-level` section.
1168
1169**webpack.config.js**
1170
1171```js
1172const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1173
1174module.exports = {
1175 optimization: {
1176 minimizer: [
1177 "...",
1178 new ImageMinimizerPlugin({
1179 generator: [
1180 {
1181 preset: "name",
1182 filename: "generated-[name][ext]",
1183 implementation: ImageMinimizerPlugin.squooshMinify,
1184 // Options
1185 options: {
1186 encodeOptions: {
1187 mozjpeg: {
1188 quality: 90,
1189 },
1190 },
1191 },
1192 },
1193 ],
1194 }),
1195 ],
1196 },
1197};
1198```
1199
1200Example of `Function` usage:
1201
1202**webpack.config.js**
1203
1204```js
1205const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1206
1207module.exports = {
1208 optimization: {
1209 minimizer: [
1210 "...",
1211 new ImageMinimizerPlugin({
1212 generator: [
1213 {
1214 preset: "name",
1215 filename: () => "generated-[name][ext]",
1216 implementation: ImageMinimizerPlugin.squooshMinify,
1217 // Options
1218 options: {
1219 encodeOptions: {
1220 mozjpeg: {
1221 quality: 90,
1222 },
1223 },
1224 },
1225 },
1226 ],
1227 }),
1228 ],
1229 },
1230};
1231```
1232
1233#### `severityError`
1234
1235Type: `String`
1236Default: `'error'`
1237
1238Allows to choose how errors are displayed.
1239
1240Сan have the following values:
1241
1242- `'off'` - suppresses errors and warnings
1243- `'warning'` - emit warnings instead errors
1244- `'error'` - emit errors
1245
1246**webpack.config.js**
1247
1248```js
1249const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1250
1251module.exports = {
1252 optimization: {
1253 minimizer: [
1254 "...",
1255 new ImageMinimizerPlugin({
1256 severityError: "warning",
1257 minimizer: {
1258 implementation: ImageMinimizerPlugin.imageminMinify,
1259 options: {
1260 plugins: [
1261 "imagemin-gifsicle",
1262 "imagemin-mozjpeg",
1263 "imagemin-pngquant",
1264 "imagemin-svgo",
1265 ],
1266 },
1267 },
1268 }),
1269 ],
1270 },
1271};
1272```
1273
1274#### `loader`
1275
1276Type: `Boolean`
1277Default: `true`
1278
1279Automatically adding built-in `loader`, used to optimize/generate images.
1280
1281**webpack.config.js**
1282
1283```js
1284const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1285
1286module.exports = {
1287 optimization: {
1288 minimizer: [
1289 "...",
1290 new ImageMinimizerPlugin({
1291 loader: false,
1292 // `generator` will not work in this case
1293 minimizer: {
1294 implementation: ImageMinimizerPlugin.imageminMinify,
1295 options: {
1296 plugins: [
1297 "imagemin-gifsicle",
1298 "imagemin-mozjpeg",
1299 "imagemin-pngquant",
1300 "imagemin-svgo",
1301 ],
1302 },
1303 },
1304 }),
1305 ],
1306 },
1307};
1308```
1309
1310#### `concurrency`
1311
1312Type: `Number`
1313Default: `Math.max(1, os.cpus().length - 1)`
1314
1315Maximum number of concurrency optimization processes in one time.
1316
1317**webpack.config.js**
1318
1319```js
1320const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1321
1322module.exports = {
1323 optimization: {
1324 minimizer: [
1325 "...",
1326 new ImageMinimizerPlugin({
1327 concurrency: 3,
1328 minimizer: {
1329 implementation: ImageMinimizerPlugin.imageminMinify,
1330 options: {
1331 plugins: [
1332 "imagemin-gifsicle",
1333 "imagemin-mozjpeg",
1334 "imagemin-pngquant",
1335 "imagemin-svgo",
1336 ],
1337 },
1338 },
1339 }),
1340 ],
1341 },
1342};
1343```
1344
1345#### `deleteOriginalAssets`
1346
1347Type: `Boolean`
1348Default: `true`
1349
1350Allows removing original assets after optimization.
1351
1352**Please use this option if you are set the `filename` option for the `minimizer` option, disable `loader: false` and want to keep optimized and not optimized assets.**
1353
1354**webpack.config.js**
1355
1356```js
1357const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1358
1359module.exports = {
1360 optimization: {
1361 minimizer: [
1362 "...",
1363 new ImageMinimizerPlugin({
1364 // Disable loader
1365 loader: false,
1366 // Allows to keep original asset and minimized assets with different filenames
1367 deleteOriginalAssets: false,
1368 minimizer: {
1369 filename: "[path][name].webp",
1370 implementation: ImageMinimizerPlugin.imageminMinify,
1371 options: {
1372 plugins: [
1373 "imagemin-gifsicle",
1374 "imagemin-mozjpeg",
1375 "imagemin-pngquant",
1376 "imagemin-svgo",
1377 ],
1378 },
1379 },
1380 }),
1381 ],
1382 },
1383};
1384```
1385
1386### Loader Options
1387
1388| Name | Type | Default | Description |
1389| :------------------------------------: | :-------------------------: | :---------: | :---------------------------------------- |
1390| **[`minimizer`](#minimizer-1)** | `{Object \| Array<Object>}` | `undefined` | Allows to setup default minimizer |
1391| **[`generator`](#generator-1)** | `{Array<Object>}` | `undefined` | Allows to setup default generator |
1392| **[`severityError`](severityerror-1)** | `{String}` | `'error'` | Allows to choose how errors are displayed |
1393
1394#### `severityError`
1395
1396Type: `String`
1397Default: `'error'`
1398
1399Allows to choose how errors are displayed.
1400
1401Сan have the following values:
1402
1403- `'off'` - suppresses errors and warnings
1404- `'warning'` - emit warnings instead errors
1405- `'error'` - emit errors
1406
1407**webpack.config.js**
1408
1409```js
1410const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1411
1412module.exports = {
1413 module: {
1414 rules: [
1415 {
1416 test: /\.(jpe?g|png|gif|svg)$/i,
1417 type: "asset",
1418 },
1419 {
1420 test: /\.(jpe?g|png|gif|svg)$/i,
1421 use: [
1422 {
1423 loader: ImageMinimizerPlugin.loader,
1424 options: {
1425 severityError: "warning",
1426 minimizerOptions: {
1427 plugins: ["gifsicle"],
1428 },
1429 },
1430 },
1431 ],
1432 },
1433 ],
1434 },
1435};
1436```
1437
1438#### `minimizer`
1439
1440Type: `Object|Array<Object>`
1441Default: `undefined`
1442
1443Allows to setup default minimizer.
1444
1445##### `Object`
1446
1447**webpack.config.js**
1448
1449```js
1450const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1451
1452module.exports = {
1453 module: {
1454 rules: [
1455 {
1456 test: /\.(jpe?g|png|gif|svg)$/i,
1457 type: "asset",
1458 },
1459 {
1460 test: /\.(jpe?g|png|gif|svg)$/i,
1461 loader: ImageMinimizerPlugin.loader,
1462 enforce: "pre",
1463 options: {
1464 minimizer: {
1465 implementation: ImageMinimizerPlugin.squooshMinify,
1466 options: {
1467 // Your options
1468 },
1469 },
1470 },
1471 },
1472 ],
1473 },
1474};
1475```
1476
1477For more information and supported options please read [here](#minimizer).
1478
1479### `generator`
1480
1481Type: `Array<Object>`
1482Default: `undefined`
1483
1484Allow to setup default generators.
1485Useful if you need generate `webp`/`avif`/etc from other formats.
1486
1487**webpack.config.js**
1488
1489```js
1490const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1491
1492module.exports = {
1493 module: {
1494 rules: [
1495 {
1496 test: /\.(jpe?g|png|gif|svg)$/i,
1497 type: "asset",
1498 },
1499 {
1500 test: /\.(jpe?g|png|gif|svg)$/i,
1501 loader: ImageMinimizerPlugin.loader,
1502 enforce: "pre",
1503 options: {
1504 generator: [
1505 {
1506 preset: "webp",
1507 implementation: ImageMinimizerPlugin.imageminGenerate,
1508 options: {
1509 plugins: ["iamgemin-webp"],
1510 },
1511 },
1512 ],
1513 },
1514 },
1515 ],
1516 },
1517};
1518```
1519
1520For more information and supported options please read [here](#generator).
1521
1522## Additional API
1523
1524### `imageminNormalizeConfig(config)`
1525
1526The function normalizes configuration (converts plugins names and options to `Function`s) for using in `imagemin` package directly.
1527
1528```js
1529const imagemin = require("imagemin");
1530const { imageminNormalizeConfig } = require("image-minimizer-webpack-plugin");
1531
1532/*
1533 console.log(imageminConfig);
1534 =>
1535 {
1536 plugins: [Function, Function],
1537 pluginsMeta: [
1538 { name: "imagemin-jpegtran", version: "x.x.x", options: {} },
1539 { name: "imagemin-pngquant", version: "x.x.x", options: { quality: [0.6, 0.8] }
1540 ]
1541 }
1542*/
1543
1544(async () => {
1545 const imageminConfig = await imageminNormalizeConfig({
1546 plugins: ["jpegtran", ["pngquant", { quality: [0.6, 0.8] }]],
1547 });
1548 const files = await imagemin(["images/*.{jpg,png}"], {
1549 destination: "build/images",
1550 plugins: imageminConfig.plugins,
1551 });
1552
1553 console.log(files);
1554 // => [{data: <Buffer 89 50 4e …>, path: 'build/images/foo.jpg'}, …]
1555})();
1556```
1557
1558## Examples
1559
1560### Optimize images based on size
1561
1562You can use difference options (like `progressive`/`interlaced`/etc.) based on image size (example - don't do progressive transformation for small images).
1563
1564What is `progressive` image? [`Answer here`](https://jmperezperez.com/medium-image-progressive-loading-placeholder/).
1565
1566**webpack.config.js**
1567
1568```js
1569const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1570
1571module.exports = {
1572 optimization: {
1573 minimizer: [
1574 new ImageMinimizerPlugin({
1575 minimizer: {
1576 implementation: ImageMinimizerPlugin.imageminMinify,
1577 options: {
1578 plugins: [["jpegtran", { progressive: true }]],
1579 },
1580 // Only apply this one to files equal to or over 8192 bytes
1581 filter: (source) => {
1582 if (source.byteLength >= 8192) {
1583 return true;
1584 }
1585
1586 return false;
1587 },
1588 },
1589 }),
1590 new ImageMinimizerPlugin({
1591 minimizer: {
1592 implementation: ImageMinimizerPlugin.imageminMinify,
1593 options: {
1594 plugins: [["jpegtran", { progressive: false }]],
1595 },
1596 // Only apply this one to files under 8192
1597 filter: (source) => {
1598 if (source.byteLength < 8192) {
1599 return true;
1600 }
1601
1602 return false;
1603 },
1604 },
1605 }),
1606 ],
1607 },
1608};
1609```
1610
1611### Optimize and generate `webp` images
1612
1613- imagemin
1614
1615**webpack.config.js**
1616
1617```js
1618const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1619
1620module.exports = {
1621 optimization: {
1622 minimizer: [
1623 "...",
1624 new ImageMinimizerPlugin({
1625 minimizer: {
1626 implementation: ImageMinimizerPlugin.imageminMinify,
1627 options: {
1628 plugins: [
1629 "imagemin-gifsicle",
1630 "imagemin-mozjpeg",
1631 "imagemin-pngquant",
1632 "imagemin-svgo",
1633 ],
1634 },
1635 },
1636 generator: [
1637 {
1638 // You can apply generator using `?as=webp`, you can use any name and provide more options
1639 preset: "webp",
1640 implementation: ImageMinimizerPlugin.imageminGenerate,
1641 options: {
1642 plugins: ["imagemin-webp"],
1643 },
1644 },
1645 ],
1646 }),
1647 ],
1648 },
1649};
1650```
1651
1652- squoosh
1653
1654**webpack.config.js**
1655
1656```js
1657const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1658
1659module.exports = {
1660 optimization: {
1661 minimizer: [
1662 "...",
1663 new ImageMinimizerPlugin({
1664 minimizer: {
1665 implementation: ImageMinimizerPlugin.squooshMinify,
1666 },
1667 generator: [
1668 {
1669 // You can apply generator using `?as=webp`, you can use any name and provide more options
1670 preset: "webp",
1671 implementation: ImageMinimizerPlugin.squooshGenerate,
1672 options: {
1673 encodeOptions: {
1674 webp: {
1675 quality: 90,
1676 },
1677 },
1678 },
1679 },
1680 ],
1681 }),
1682 ],
1683 },
1684};
1685```
1686
1687### Generate `webp` images from copied assets
1688
1689- imagemin
1690
1691**webpack.config.js**
1692
1693```js
1694const CopyPlugin = require("copy-webpack-plugin");
1695const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1696
1697module.exports = {
1698 optimization: {
1699 minimizer: [
1700 "...",
1701 new ImageMinimizerPlugin({
1702 minimizer: {
1703 implementation: ImageMinimizerPlugin.imageminMinify,
1704 options: {
1705 plugins: [
1706 "imagemin-gifsicle",
1707 "imagemin-mozjpeg",
1708 "imagemin-pngquant",
1709 "imagemin-svgo",
1710 ],
1711 },
1712 },
1713 generator: [
1714 {
1715 type: "asset",
1716 implementation: ImageMinimizerPlugin.imageminGenerate,
1717 options: {
1718 plugins: ["imagemin-webp"],
1719 },
1720 },
1721 ],
1722 }),
1723 ],
1724 },
1725 plugnins: [new CopyPlugin({ patterns: ["images/**/*.png"] })],
1726};
1727```
1728
1729- squoosh
1730
1731**webpack.config.js**
1732
1733```js
1734const CopyPlugin = require("copy-webpack-plugin");
1735const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1736
1737module.exports = {
1738 optimization: {
1739 minimizer: [
1740 "...",
1741 new ImageMinimizerPlugin({
1742 minimizer: {
1743 implementation: ImageMinimizerPlugin.squooshMinify,
1744 },
1745 generator: [
1746 {
1747 type: "asset",
1748 implementation: ImageMinimizerPlugin.squooshGenerate,
1749 options: {
1750 encodeOptions: {
1751 webp: {
1752 quality: 90,
1753 },
1754 },
1755 },
1756 },
1757 ],
1758 }),
1759 ],
1760 },
1761 plugnins: [new CopyPlugin({ patterns: ["images/**/*.png"] })],
1762};
1763```
1764
1765## Contributing
1766
1767Please take a moment to read our contributing guidelines if you haven't yet done so.
1768
1769[CONTRIBUTING](./.github/CONTRIBUTING.md)
1770
1771## License
1772
1773[MIT](./LICENSE)
1774
1775[npm]: https://img.shields.io/npm/v/image-minimizer-webpack-plugin.svg
1776[npm-url]: https://npmjs.com/package/image-minimizer-webpack-plugin
1777[node]: https://img.shields.io/node/v/image-minimizer-webpack-plugin.svg
1778[node-url]: https://nodejs.org
1779[deps]: https://david-dm.org/webpack-contrib/image-minimizer-webpack-plugin.svg
1780[deps-url]: https://david-dm.org/webpack-contrib/image-minimizer-webpack-plugin
1781[tests]: https://github.com/webpack-contrib/image-minimizer-webpack-plugin/workflows/image-minimizer-webpack-plugin/badge.svg
1782[tests-url]: https://github.com/webpack-contrib/image-minimizer-webpack-plugin/actions
1783[cover]: https://codecov.io/gh/webpack-contrib/image-minimizer-webpack-plugin/branch/master/graph/badge.svg
1784[cover-url]: https://codecov.io/gh/webpack-contrib/image-minimizer-webpack-plugin
1785[chat]: https://badges.gitter.im/webpack/webpack.svg
1786[chat-url]: https://gitter.im/webpack/webpack
1787[size]: https://packagephobia.now.sh/badge?p=image-minimizer-webpack-plugin
1788[size-url]: https://packagephobia.now.sh/result?p=image-minimizer-webpack-plugin