UNPKG

41.7 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###### `preset`
969
970Type: `String`
971Default: `undefined`
972
973Configure the name of preset, i.e. you can use it in `?as=name`.
974
975**webpack.config.js**
976
977```js
978const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
979
980module.exports = {
981 optimization: {
982 minimizer: [
983 "...",
984 new ImageMinimizerPlugin({
985 generator: [
986 {
987 preset: "name",
988 // Implementation
989 implementation: ImageMinimizerPlugin.squooshMinify,
990 },
991 ],
992 }),
993 ],
994 },
995};
996```
997
998###### `implementation`
999
1000Type: `Function`
1001Default: `undefined`
1002
1003Configure the default `implementation`.
1004
1005**webpack.config.js**
1006
1007```js
1008const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1009
1010module.exports = {
1011 optimization: {
1012 minimizer: [
1013 "...",
1014 new ImageMinimizerPlugin({
1015 generator: [
1016 {
1017 preset: "name",
1018 // Implementation
1019 implementation: ImageMinimizerPlugin.squooshMinify,
1020 },
1021 ],
1022 }),
1023 ],
1024 },
1025};
1026```
1027
1028###### `options`
1029
1030Type: `Object`
1031Default: `undefined`
1032
1033Options for the `implementation` option (i.e. options for `imagemin`/`squoosh`/custom implementation).
1034
1035**webpack.config.js**
1036
1037```js
1038const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1039
1040module.exports = {
1041 optimization: {
1042 minimizer: [
1043 "...",
1044 new ImageMinimizerPlugin({
1045 generator: [
1046 {
1047 preset: "name",
1048 implementation: ImageMinimizerPlugin.squooshMinify,
1049 // Options
1050 options: {
1051 encodeOptions: {
1052 mozjpeg: {
1053 quality: 90,
1054 },
1055 },
1056 },
1057 },
1058 ],
1059 }),
1060 ],
1061 },
1062};
1063```
1064
1065###### `filter`
1066
1067Type: `Function`
1068Default: `() => true`
1069
1070Allows filtering of images for optimization/generation.
1071
1072Return `true` to optimize the image, `false` otherwise.
1073
1074**webpack.config.js**
1075
1076```js
1077const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1078
1079module.exports = {
1080 optimization: {
1081 minimizer: [
1082 "...",
1083 new ImageMinimizerPlugin({
1084 generator: [
1085 {
1086 preset: "name",
1087 filter: (source, sourcePath) => {
1088 // The `source` argument is a `Buffer` of source file
1089 // The `sourcePath` argument is an absolute path to source
1090 if (source.byteLength < 8192) {
1091 return false;
1092 }
1093
1094 return true;
1095 },
1096 implementation: ImageMinimizerPlugin.imageminMinify,
1097 options: {
1098 plugins: [
1099 "imagemin-gifsicle",
1100 "imagemin-mozjpeg",
1101 "imagemin-pngquant",
1102 "imagemin-svgo",
1103 ],
1104 },
1105 },
1106 ],
1107 }),
1108 ],
1109 },
1110};
1111```
1112
1113###### `filename`
1114
1115Type: `string | Function`
1116Default: `undefined`
1117
1118Allows to set the filename.
1119Supported values see in [`webpack template strings`](https://webpack.js.org/configuration/output/#template-strings), `File-level` section.
1120
1121**webpack.config.js**
1122
1123```js
1124const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1125
1126module.exports = {
1127 optimization: {
1128 minimizer: [
1129 "...",
1130 new ImageMinimizerPlugin({
1131 generator: [
1132 {
1133 preset: "name",
1134 filename: "generated-[name][ext]",
1135 implementation: ImageMinimizerPlugin.squooshMinify,
1136 // Options
1137 options: {
1138 encodeOptions: {
1139 mozjpeg: {
1140 quality: 90,
1141 },
1142 },
1143 },
1144 },
1145 ],
1146 }),
1147 ],
1148 },
1149};
1150```
1151
1152Example of `Function` usage:
1153
1154**webpack.config.js**
1155
1156```js
1157const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1158
1159module.exports = {
1160 optimization: {
1161 minimizer: [
1162 "...",
1163 new ImageMinimizerPlugin({
1164 generator: [
1165 {
1166 preset: "name",
1167 filename: () => "generated-[name][ext]",
1168 implementation: ImageMinimizerPlugin.squooshMinify,
1169 // Options
1170 options: {
1171 encodeOptions: {
1172 mozjpeg: {
1173 quality: 90,
1174 },
1175 },
1176 },
1177 },
1178 ],
1179 }),
1180 ],
1181 },
1182};
1183```
1184
1185#### `severityError`
1186
1187Type: `String`
1188Default: `'error'`
1189
1190Allows to choose how errors are displayed.
1191
1192Сan have the following values:
1193
1194- `'off'` - suppresses errors and warnings
1195- `'warning'` - emit warnings instead errors
1196- `'error'` - emit errors
1197
1198**webpack.config.js**
1199
1200```js
1201const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1202
1203module.exports = {
1204 optimization: {
1205 minimizer: [
1206 "...",
1207 new ImageMinimizerPlugin({
1208 severityError: "warning",
1209 minimizer: {
1210 implementation: ImageMinimizerPlugin.imageminMinify,
1211 options: {
1212 plugins: [
1213 "imagemin-gifsicle",
1214 "imagemin-mozjpeg",
1215 "imagemin-pngquant",
1216 "imagemin-svgo",
1217 ],
1218 },
1219 },
1220 }),
1221 ],
1222 },
1223};
1224```
1225
1226#### `loader`
1227
1228Type: `Boolean`
1229Default: `true`
1230
1231Automatically adding built-in `loader`, used to optimize/generate images.
1232
1233**webpack.config.js**
1234
1235```js
1236const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1237
1238module.exports = {
1239 optimization: {
1240 minimizer: [
1241 "...",
1242 new ImageMinimizerPlugin({
1243 loader: false,
1244 // `generator` will not work in this case
1245 minimizer: {
1246 implementation: ImageMinimizerPlugin.imageminMinify,
1247 options: {
1248 plugins: [
1249 "imagemin-gifsicle",
1250 "imagemin-mozjpeg",
1251 "imagemin-pngquant",
1252 "imagemin-svgo",
1253 ],
1254 },
1255 },
1256 }),
1257 ],
1258 },
1259};
1260```
1261
1262#### `concurrency`
1263
1264Type: `Number`
1265Default: `Math.max(1, os.cpus().length - 1)`
1266
1267Maximum number of concurrency optimization processes in one time.
1268
1269**webpack.config.js**
1270
1271```js
1272const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1273
1274module.exports = {
1275 optimization: {
1276 minimizer: [
1277 "...",
1278 new ImageMinimizerPlugin({
1279 concurrency: 3,
1280 minimizer: {
1281 implementation: ImageMinimizerPlugin.imageminMinify,
1282 options: {
1283 plugins: [
1284 "imagemin-gifsicle",
1285 "imagemin-mozjpeg",
1286 "imagemin-pngquant",
1287 "imagemin-svgo",
1288 ],
1289 },
1290 },
1291 }),
1292 ],
1293 },
1294};
1295```
1296
1297#### `deleteOriginalAssets`
1298
1299Type: `Boolean`
1300Default: `true`
1301
1302Allows removing original assets after optimization.
1303
1304**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.**
1305
1306**webpack.config.js**
1307
1308```js
1309const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1310
1311module.exports = {
1312 optimization: {
1313 minimizer: [
1314 "...",
1315 new ImageMinimizerPlugin({
1316 // Disable loader
1317 loader: false,
1318 // Allows to keep original asset and minimized assets with different filenames
1319 deleteOriginalAssets: false,
1320 minimizer: {
1321 filename: "[path][name].webp",
1322 implementation: ImageMinimizerPlugin.imageminMinify,
1323 options: {
1324 plugins: [
1325 "imagemin-gifsicle",
1326 "imagemin-mozjpeg",
1327 "imagemin-pngquant",
1328 "imagemin-svgo",
1329 ],
1330 },
1331 },
1332 }),
1333 ],
1334 },
1335};
1336```
1337
1338### Loader Options
1339
1340| Name | Type | Default | Description |
1341| :------------------------------------: | :-------------------------: | :---------: | :---------------------------------------- |
1342| **[`minimizer`](#minimizer-1)** | `{Object \| Array<Object>}` | `undefined` | Allows to setup default minimizer |
1343| **[`generator`](#generator-1)** | `{Array<Object>}` | `undefined` | Allows to setup default generator |
1344| **[`severityError`](severityerror-1)** | `{String}` | `'error'` | Allows to choose how errors are displayed |
1345
1346#### `severityError`
1347
1348Type: `String`
1349Default: `'error'`
1350
1351Allows to choose how errors are displayed.
1352
1353Сan have the following values:
1354
1355- `'off'` - suppresses errors and warnings
1356- `'warning'` - emit warnings instead errors
1357- `'error'` - emit errors
1358
1359**webpack.config.js**
1360
1361```js
1362const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1363
1364module.exports = {
1365 module: {
1366 rules: [
1367 {
1368 test: /\.(jpe?g|png|gif|svg)$/i,
1369 type: "asset",
1370 },
1371 {
1372 test: /\.(jpe?g|png|gif|svg)$/i,
1373 use: [
1374 {
1375 loader: ImageMinimizerPlugin.loader,
1376 options: {
1377 severityError: "warning",
1378 minimizerOptions: {
1379 plugins: ["gifsicle"],
1380 },
1381 },
1382 },
1383 ],
1384 },
1385 ],
1386 },
1387};
1388```
1389
1390#### `minimizer`
1391
1392Type: `Object|Array<Object>`
1393Default: `undefined`
1394
1395Allows to setup default minimizer.
1396
1397##### `Object`
1398
1399**webpack.config.js**
1400
1401```js
1402const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1403
1404module.exports = {
1405 module: {
1406 rules: [
1407 {
1408 test: /\.(jpe?g|png|gif|svg)$/i,
1409 type: "asset",
1410 },
1411 {
1412 test: /\.(jpe?g|png|gif|svg)$/i,
1413 loader: ImageMinimizerPlugin.loader,
1414 enforce: "pre",
1415 options: {
1416 minimizer: {
1417 implementation: ImageMinimizerPlugin.squooshMinify,
1418 options: {
1419 // Your options
1420 },
1421 },
1422 },
1423 },
1424 ],
1425 },
1426};
1427```
1428
1429For more information and supported options please read [here](#minimizer).
1430
1431### `generator`
1432
1433Type: `Array<Object>`
1434Default: `undefined`
1435
1436Allow to setup default generators.
1437Useful if you need generate `webp`/`avif`/etc from other formats.
1438
1439**webpack.config.js**
1440
1441```js
1442const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1443
1444module.exports = {
1445 module: {
1446 rules: [
1447 {
1448 test: /\.(jpe?g|png|gif|svg)$/i,
1449 type: "asset",
1450 },
1451 {
1452 test: /\.(jpe?g|png|gif|svg)$/i,
1453 loader: ImageMinimizerPlugin.loader,
1454 enforce: "pre",
1455 options: {
1456 generator: [
1457 {
1458 preset: "webp",
1459 implementation: ImageMinimizerPlugin.imageminGenerate,
1460 options: {
1461 plugins: ["iamgemin-webp"],
1462 },
1463 },
1464 ],
1465 },
1466 },
1467 ],
1468 },
1469};
1470```
1471
1472For more information and supported options please read [here](#generator).
1473
1474## Additional API
1475
1476### `imageminNormalizeConfig(config)`
1477
1478The function normalizes configuration (converts plugins names and options to `Function`s) for using in `imagemin` package directly.
1479
1480```js
1481const imagemin = require("imagemin");
1482const { imageminNormalizeConfig } = require("image-minimizer-webpack-plugin");
1483
1484/*
1485 console.log(imageminConfig);
1486 =>
1487 {
1488 plugins: [Function, Function],
1489 pluginsMeta: [
1490 { name: "imagemin-jpegtran", version: "x.x.x", options: {} },
1491 { name: "imagemin-pngquant", version: "x.x.x", options: { quality: [0.6, 0.8] }
1492 ]
1493 }
1494*/
1495
1496(async () => {
1497 const imageminConfig = await imageminNormalizeConfig({
1498 plugins: ["jpegtran", ["pngquant", { quality: [0.6, 0.8] }]],
1499 });
1500 const files = await imagemin(["images/*.{jpg,png}"], {
1501 destination: "build/images",
1502 plugins: imageminConfig.plugins,
1503 });
1504
1505 console.log(files);
1506 // => [{data: <Buffer 89 50 4e …>, path: 'build/images/foo.jpg'}, …]
1507})();
1508```
1509
1510## Examples
1511
1512### Optimize images based on size
1513
1514You can use difference options (like `progressive`/`interlaced`/etc.) based on image size (example - don't do progressive transformation for small images).
1515
1516What is `progressive` image? [`Answer here`](https://jmperezperez.com/medium-image-progressive-loading-placeholder/).
1517
1518**webpack.config.js**
1519
1520```js
1521const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1522
1523module.exports = {
1524 optimization: {
1525 minimizer: [
1526 new ImageMinimizerPlugin({
1527 minimizer: {
1528 implementation: ImageMinimizerPlugin.imageminMinify,
1529 options: {
1530 plugins: [["jpegtran", { progressive: true }]],
1531 },
1532 // Only apply this one to files equal to or over 8192 bytes
1533 filter: (source) => {
1534 if (source.byteLength >= 8192) {
1535 return true;
1536 }
1537
1538 return false;
1539 },
1540 },
1541 }),
1542 new ImageMinimizerPlugin({
1543 minimizer: {
1544 implementation: ImageMinimizerPlugin.imageminMinify,
1545 options: {
1546 plugins: [["jpegtran", { progressive: false }]],
1547 },
1548 // Only apply this one to files under 8192
1549 filter: (source) => {
1550 if (source.byteLength < 8192) {
1551 return true;
1552 }
1553
1554 return false;
1555 },
1556 },
1557 }),
1558 ],
1559 },
1560};
1561```
1562
1563### Optimize and generate `webp` images
1564
1565- imagemin
1566
1567**webpack.config.js**
1568
1569```js
1570const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1571
1572module.exports = {
1573 optimization: {
1574 minimizer: [
1575 "...",
1576 new ImageMinimizerPlugin({
1577 minimizer: {
1578 implementation: ImageMinimizerPlugin.imageminMinify,
1579 options: {
1580 plugins: [
1581 "imagemin-gifsicle",
1582 "imagemin-mozjpeg",
1583 "imagemin-pngquant",
1584 "imagemin-svgo",
1585 ],
1586 },
1587 },
1588 generator: [
1589 {
1590 // You can apply generator using `?as=webp`, you can use any name and provide more options
1591 preset: "webp",
1592 implementation: ImageMinimizerPlugin.imageminGenerate,
1593 options: {
1594 plugins: ["imagemin-webp"],
1595 },
1596 },
1597 ],
1598 }),
1599 ],
1600 },
1601};
1602```
1603
1604- squoosh
1605
1606**webpack.config.js**
1607
1608```js
1609const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1610
1611module.exports = {
1612 optimization: {
1613 minimizer: [
1614 "...",
1615 new ImageMinimizerPlugin({
1616 minimizer: {
1617 implementation: ImageMinimizerPlugin.squooshMinify,
1618 },
1619 generator: [
1620 {
1621 // You can apply generator using `?as=webp`, you can use any name and provide more options
1622 preset: "webp",
1623 implementation: ImageMinimizerPlugin.squooshGenerate,
1624 options: {
1625 encodeOptions: {
1626 webp: {
1627 quality: 90,
1628 },
1629 },
1630 },
1631 },
1632 ],
1633 }),
1634 ],
1635 },
1636};
1637```
1638
1639## Contributing
1640
1641Please take a moment to read our contributing guidelines if you haven't yet done so.
1642
1643[CONTRIBUTING](./.github/CONTRIBUTING.md)
1644
1645## License
1646
1647[MIT](./LICENSE)
1648
1649[npm]: https://img.shields.io/npm/v/image-minimizer-webpack-plugin.svg
1650[npm-url]: https://npmjs.com/package/image-minimizer-webpack-plugin
1651[node]: https://img.shields.io/node/v/image-minimizer-webpack-plugin.svg
1652[node-url]: https://nodejs.org
1653[deps]: https://david-dm.org/webpack-contrib/image-minimizer-webpack-plugin.svg
1654[deps-url]: https://david-dm.org/webpack-contrib/image-minimizer-webpack-plugin
1655[tests]: https://github.com/webpack-contrib/image-minimizer-webpack-plugin/workflows/image-minimizer-webpack-plugin/badge.svg
1656[tests-url]: https://github.com/webpack-contrib/image-minimizer-webpack-plugin/actions
1657[cover]: https://codecov.io/gh/webpack-contrib/image-minimizer-webpack-plugin/branch/master/graph/badge.svg
1658[cover-url]: https://codecov.io/gh/webpack-contrib/image-minimizer-webpack-plugin
1659[chat]: https://badges.gitter.im/webpack/webpack.svg
1660[chat-url]: https://gitter.im/webpack/webpack
1661[size]: https://packagephobia.now.sh/badge?p=image-minimizer-webpack-plugin
1662[size-url]: https://packagephobia.now.sh/result?p=image-minimizer-webpack-plugin