UNPKG

63.9 kBMarkdownView Raw
1<!--lint disable no-html-->
2<div align="center">
3 <a href="https://github.com/webpack/webpack">
4 <img width="200" height="200" hspace="10"
5 src="https://cdn.rawgit.com/webpack/media/e7485eb2/logo/icon.svg">
6 </a>
7 <h1>Imagemin Webpack</h1>
8 <p>
9 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>.
10 Do not worry about size of images, now they are always optimized/compressed.
11 </p>
12</div>
13
14<!--lint enable no-html-->
15
16[![npm][npm]][npm-url]
17[![node][node]][node-url]
18[![tests][tests]][tests-url]
19[![cover][cover]][cover-url]
20[![discussion][discussion]][discussion-url]
21[![size][size]][size-url]
22
23# image-minimizer-webpack-plugin
24
25<!--
26This TOC was generated by VS Code extension [Markdown All in One](https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one)
27with option `"markdown.extension.toc.levels": "2..6"`
28-->
29
30- [Getting Started](#getting-started)
31 - [Install optimize/generate tool](#install-optimizegenerate-tool)
32 - [Optimize with `imagemin`](#optimize-with-imagemin)
33 - [[**DEPRECATED**] Optimize with `squoosh`](#optimize-with-squoosh)
34 - [Optimize with `sharp`](#optimize-with-sharp)
35 - [Optimize with `svgo`](#optimize-with-svgo)
36 - [Advanced setup](#advanced-setup)
37 - [Query Parameters (only `squoosh` and `sharp` currently)](#query-parameters-only-squoosh-and-sharp-currently)
38 - [Standalone Loader](#standalone-loader)
39 - [Standalone Plugin](#standalone-plugin)
40- [Plugin Options](#plugin-options)
41 - [`test`](#test)
42 - [`include`](#include)
43 - [`exclude`](#exclude)
44 - [`minimizer`](#minimizer)
45 - [Available minimizers](#available-minimizers)
46 - [Single minimizer example for `imagemin`](#single-minimizer-example-for-imagemin)
47 - [[**DEPRECATED**] Single minimizer example for `squoosh`](#single-minimizer-example-for-squoosh)
48 - [Single minimizer example for `sharp`](#single-minimizer-example-for-sharp)
49 - [Single minimizer example for user defined implementation](#single-minimizer-example-for-user-defined-implementation)
50 - [Multiple minimizers example](#multiple-minimizers-example)
51 - [Minimizer options](#minimizer-options)
52 - [`implementation`](#implementation)
53 - [`options`](#options)
54 - [`filter`](#filter)
55 - [`filename`](#filename)
56 - [`generator`](#generator)
57 - [Available generators](#available-generators)
58 - [Generator example for `imagemin`](#generator-example-for-imagemin)
59 - [[**DEPRECATED**] Generator example for `squoosh`](#generator-example-for-squoosh)
60 - [Generator example for `sharp`](#generator-example-for-sharp)
61 - [Generator example for user defined implementation](#generator-example-for-user-defined-implementation)
62 - [Generator options](#generator-options)
63 - [`type`](#type)
64 - [`preset`](#preset)
65 - [`implementation`](#implementation-1)
66 - [`options`](#options-1)
67 - [`filter`](#filter-1)
68 - [`filename`](#filename-1)
69 - [`severityError`](#severityerror)
70 - [`loader`](#loader)
71 - [`concurrency`](#concurrency)
72 - [`deleteOriginalAssets`](#deleteoriginalassets)
73- [Loader Options](#loader-options)
74 - [`minimizer`](#minimizer-1)
75 - [Loader minimizer example for `imagemin`](#loader-minimizer-example-for-imagemin)
76 - [`generator`](#generator-1)
77 - [Loader generator example for `imagemin`](#loader-generator-example-for-imagemin)
78 - [`severityError`](#severityerror-1)
79- [Additional API](#additional-api)
80 - [`imageminNormalizeConfig(config)`](#imageminnormalizeconfigconfig)
81- [Examples](#examples)
82 - [Optimize images based on size](#optimize-images-based-on-size)
83 - [Optimize and generate `webp` images](#optimize-and-generate-webp-images)
84 - [Generate `webp` images from copied assets](#generate-webp-images-from-copied-assets)
85- [Contributing](#contributing)
86- [License](#license)
87
88## Getting Started
89
90This plugin can use 4 tools to optimize/generate images:
91
92- [`imagemin`](https://github.com/imagemin/imagemin) - optimize your images by default, since it is stable and works with all types of images
93- **DEPRECATED** [`squoosh`](https://github.com/GoogleChromeLabs/squoosh/tree/dev/libsquoosh) - while working in experimental mode with `.jpg`, `.jpeg`, `.png`, `.webp`, `.avif` file types.
94- [`sharp`](https://github.com/lovell/sharp) - High performance Node.js image processing, the fastest module to resize and compress JPEG, PNG, WebP, AVIF and TIFF images. Uses the libvips library.
95- [`svgo`](https://github.com/svg/svgo) - tool for optimizing SVG vector graphics files. Supports only SVG files minification.
96
97> **Warning**
98>
99> By default we don't install anything
100
101### Install optimize/generate tool
102
103To begin, you'll need to install `image-minimizer-webpack-plugin` and image minimizer/generator:
104
105- [`imagemin`](https://github.com/imagemin/imagemin):
106
107```console
108npm install image-minimizer-webpack-plugin imagemin --save-dev
109```
110
111> **Warning**
112>
113> imagemin uses plugin to optimize/generate images, so you need to install them too
114
115- **DEPRECATED** [`squoosh`](https://github.com/GoogleChromeLabs/squoosh/tree/dev/libsquoosh):
116
117```console
118npm install image-minimizer-webpack-plugin @squoosh/lib --save-dev
119```
120
121- [`sharp`](https://github.com/lovell/sharp):
122
123```console
124npm install image-minimizer-webpack-plugin sharp --save-dev
125```
126
127- [`svgo`](https://github.com/svg/svgo):
128
129```console
130npm install image-minimizer-webpack-plugin svgo --save-dev
131```
132
133Images can be optimized in two modes:
134
1351. [Lossless](https://en.wikipedia.org/wiki/Lossless_compression) (without loss of quality).
1362. [Lossy](https://en.wikipedia.org/wiki/Lossy_compression) (with loss of quality).
137
138### Optimize with [`imagemin`](https://github.com/imagemin/imagemin)
139
140> **Note**
141>
142> - [imagemin-mozjpeg](https://github.com/imagemin/imagemin-mozjpeg) can be configured in lossless and lossy mode.
143> - [imagemin-svgo](https://github.com/imagemin/imagemin-svgo) can be configured in lossless and lossy mode.
144
145Explore the options to get the best result for you.
146
147**Recommended imagemin plugins for lossless optimization**
148
149```shell
150npm install imagemin-gifsicle imagemin-jpegtran imagemin-optipng imagemin-svgo --save-dev
151```
152
153**Recommended imagemin plugins for lossy optimization**
154
155```shell
156npm install imagemin-gifsicle imagemin-mozjpeg imagemin-pngquant imagemin-svgo --save-dev
157```
158
159For `imagemin-svgo` v9.0.0+ need use svgo [configuration](https://github.com/svg/svgo#configuration)
160
161**webpack.config.js**
162
163```js
164const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
165
166module.exports = {
167 module: {
168 rules: [
169 {
170 test: /\.(jpe?g|png|gif|svg)$/i,
171 type: "asset",
172 },
173 ],
174 },
175 optimization: {
176 minimizer: [
177 "...",
178 new ImageMinimizerPlugin({
179 minimizer: {
180 implementation: ImageMinimizerPlugin.imageminMinify,
181 options: {
182 // Lossless optimization with custom option
183 // Feel free to experiment with options for better result for you
184 plugins: [
185 ["gifsicle", { interlaced: true }],
186 ["jpegtran", { progressive: true }],
187 ["optipng", { optimizationLevel: 5 }],
188 // Svgo configuration here https://github.com/svg/svgo#configuration
189 [
190 "svgo",
191 {
192 plugins: [
193 {
194 name: "preset-default",
195 params: {
196 overrides: {
197 removeViewBox: false,
198 addAttributesToSVGElement: {
199 params: {
200 attributes: [
201 { xmlns: "http://www.w3.org/2000/svg" },
202 ],
203 },
204 },
205 },
206 },
207 },
208 ],
209 },
210 ],
211 ],
212 },
213 },
214 }),
215 ],
216 },
217};
218```
219
220### **DEPRECATED** Optimize with [`squoosh`](https://github.com/GoogleChromeLabs/squoosh/tree/dev/libsquoosh)
221
222```console
223npm install @squoosh/lib --save-dev
224```
225
226**Recommended `@squoosh/lib` options for lossy optimization**
227
228For lossy optimization we recommend using the default settings of `@squoosh/lib` package.
229The 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.
230
231**webpack.config.js**
232
233```js
234const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
235
236module.exports = {
237 module: {
238 rules: [
239 // You need this, if you are using `import file from "file.ext"`, for `new URL(...)` syntax you don't need it
240 {
241 test: /\.(jpe?g|png)$/i,
242 type: "asset",
243 },
244 ],
245 },
246 optimization: {
247 minimizer: [
248 "...",
249 new ImageMinimizerPlugin({
250 minimizer: {
251 implementation: ImageMinimizerPlugin.squooshMinify,
252 options: {
253 // Your options for `squoosh`
254 },
255 },
256 }),
257 ],
258 },
259};
260```
261
262**Recommended `squoosh` options for lossless optimization**
263
264For lossless optimization we recommend using the options listed below in `minimizer.options.encodeOptions`.
265
266**webpack.config.js**
267
268```js
269const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
270
271module.exports = {
272 module: {
273 rules: [
274 // You need this, if you are using `import file from "file.ext"`, for `new URL(...)` syntax you don't need it
275 {
276 test: /\.(jpe?g|png)$/i,
277 type: "asset",
278 },
279 ],
280 },
281 optimization: {
282 minimizer: [
283 new ImageMinimizerPlugin({
284 minimizer: {
285 implementation: ImageMinimizerPlugin.squooshMinify,
286 options: {
287 encodeOptions: {
288 mozjpeg: {
289 // That setting might be close to lossless, but it’s not guaranteed
290 // https://github.com/GoogleChromeLabs/squoosh/issues/85
291 quality: 100,
292 },
293 webp: {
294 lossless: 1,
295 },
296 avif: {
297 // https://github.com/GoogleChromeLabs/squoosh/blob/dev/codecs/avif/enc/README.md
298 cqLevel: 0,
299 },
300 },
301 },
302 },
303 }),
304 ],
305 },
306};
307```
308
309### Optimize with [`sharp`](https://github.com/lovell/sharp)
310
311```console
312npm install sharp --save-dev
313```
314
315**Recommended `sharp` options for lossy optimization**
316
317For lossy optimization we recommend using the default settings of `sharp` package.
318The default values and supported file types for each option can be found in the [sharp documentation](https://sharp.pixelplumbing.com/api-output).
319
320**webpack.config.js**
321
322```js
323const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
324
325module.exports = {
326 module: {
327 rules: [
328 // You need this, if you are using `import file from "file.ext"`, for `new URL(...)` syntax you don't need it
329 {
330 test: /\.(jpe?g|png)$/i,
331 type: "asset",
332 },
333 ],
334 },
335 optimization: {
336 minimizer: [
337 "...",
338 new ImageMinimizerPlugin({
339 minimizer: {
340 implementation: ImageMinimizerPlugin.sharpMinify,
341 options: {
342 encodeOptions: {
343 // Your options for `sharp`
344 // https://sharp.pixelplumbing.com/api-output
345 },
346 },
347 },
348 }),
349 ],
350 },
351};
352```
353
354**Recommended `sharp` options for lossless optimization**
355
356For lossless optimization we recommend using the options listed below in `minimizer.options.encodeOptions`.
357
358**webpack.config.js**
359
360```js
361const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
362
363module.exports = {
364 module: {
365 rules: [
366 // You need this, if you are using `import file from "file.ext"`, for `new URL(...)` syntax you don't need it
367 {
368 test: /\.(jpe?g|png)$/i,
369 type: "asset",
370 },
371 ],
372 },
373 optimization: {
374 minimizer: [
375 new ImageMinimizerPlugin({
376 minimizer: {
377 implementation: ImageMinimizerPlugin.sharpMinify,
378 options: {
379 encodeOptions: {
380 jpeg: {
381 // https://sharp.pixelplumbing.com/api-output#jpeg
382 quality: 100,
383 },
384 webp: {
385 // https://sharp.pixelplumbing.com/api-output#webp
386 lossless: true,
387 },
388 avif: {
389 // https://sharp.pixelplumbing.com/api-output#avif
390 lossless: true,
391 },
392
393 // png by default sets the quality to 100%, which is same as lossless
394 // https://sharp.pixelplumbing.com/api-output#png
395 png: {},
396
397 // gif does not support lossless compression at all
398 // https://sharp.pixelplumbing.com/api-output#gif
399 gif: {},
400 },
401 },
402 },
403 }),
404 ],
405 },
406};
407```
408
409### Optimize with [`svgo`](https://github.com/svg/svgo)
410
411```console
412npm install svgo --save-dev
413```
414
415**Recommended `svgo` options for optimization**
416
417For optimization we recommend using the options listed below in `minimizer.options.encodeOptions`.
418The default values for plugins can be found in the [svgo plugins source code](https://github.com/svg/svgo/tree/main/plugins).
419
420**webpack.config.js**
421
422```js
423const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
424
425module.exports = {
426 module: {
427 rules: [
428 // You need this, if you are using `import file from "file.ext"`, for `new URL(...)` syntax you don't need it
429 {
430 test: /\.(svg)$/i,
431 type: "asset",
432 },
433 ],
434 },
435 optimization: {
436 minimizer: [
437 "...",
438 new ImageMinimizerPlugin({
439 minimizer: {
440 implementation: ImageMinimizerPlugin.svgoMinify,
441 options: {
442 encodeOptions: {
443 // Pass over SVGs multiple times to ensure all optimizations are applied. False by default
444 multipass: true,
445 plugins: [
446 // set of built-in plugins enabled by default
447 // see: https://github.com/svg/svgo#default-preset
448 "preset-default",
449 ],
450 },
451 },
452 },
453 }),
454 ],
455 },
456};
457```
458
459### Advanced setup
460
461If you want to use `loader` or `plugin` standalone see sections below, but this is **not recommended**.
462
463By 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.
464
465Loader 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.
466
467#### Query Parameters (only `squoosh` and `sharp` currently)
468
469The plugin supports the following query parameters:
470
471- `width`/`w` - allows you to set the image width
472- `height`/`h` - allows you to set the image height
473- `as` - to specify the [preset](#preset) option
474
475Examples:
476
477```js
478const myImage1 = new URL("image.png?width=150&height=120", import.meta.url);
479const myImage2 = new URL("image.png?w=150&h=120", import.meta.url);
480// You can omit one of the parameters to auto-scale
481const myImage3 = new URL("image.png?w=150", import.meta.url);
482// It works with the `preset` query parameter
483const myImage4 = new URL("image.png?as=webp&w=150&h=120", import.meta.url);
484// You can use `auto` to reset `width` or `height` from the `preset` option
485const myImage5 = new URL("image.png?as=webp&w=150&h=auto", import.meta.url);
486```
487
488```css
489.class {
490 background: url("./image.png?width=150&height=120");
491}
492```
493
494```html
495<picture>
496 <source srcset="photo.jpg?as=avif&width=150&height=120" type="image/avif" />
497 <source srcset="photo.jpg?as=webp&width=150&height=120" type="image/webp" />
498 <img src="photo.jpg?width=150&height=120" alt="photo" />
499</picture>
500```
501
502**NOTE**: you need to setup `avif` and `webp` presets, [example for webp](#optimize-and-generate-webp-images)
503
504#### Standalone Loader
505
506[Documentation: Using loaders](https://webpack.js.org/concepts/loaders/).
507
508In 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`):
509
510**webpack.config.js**
511
512```js
513const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
514
515module.exports = {
516 module: {
517 rules: [
518 // You need this, if you are using `import file from "file.ext"`, for `new URL(...)` syntax you don't need it
519 {
520 test: /\.(jpe?g|png|gif|svg)$/i,
521 type: "asset",
522 },
523 // We recommend using only for the "production" mode
524 {
525 test: /\.(jpe?g|png|gif|svg)$/i,
526 use: [
527 {
528 loader: ImageMinimizerPlugin.loader,
529 enforce: "pre",
530 options: {
531 minimizer: {
532 implementation: ImageMinimizerPlugin.imageminMinify,
533 options: {
534 plugins: [
535 "imagemin-gifsicle",
536 "imagemin-mozjpeg",
537 "imagemin-pngquant",
538 "imagemin-svgo",
539 ],
540 },
541 },
542 },
543 },
544 ],
545 },
546 ],
547 },
548};
549```
550
551#### Standalone Plugin
552
553[Documentation: Using plugins](https://webpack.js.org/concepts/plugins/).
554
555**webpack.config.js**
556
557```js
558const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
559
560module.exports = {
561 module: {
562 rules: [
563 // You need this, if you are using `import file from "file.ext"`, for `new URL(...)` syntax you don't need it
564 {
565 test: /\.(jpe?g|png|gif|svg)$/i,
566 type: "asset",
567 },
568 ],
569 },
570 optimization: {
571 minimizer: [
572 // Extend default minimizer, i.e. `terser-webpack-plugin` for JS
573 "...",
574 // We recommend using only for the "production" mode
575 new ImageMinimizerPlugin({
576 minimizer: {
577 implementation: ImageMinimizerPlugin.imageminMinify,
578 options: {
579 plugins: [
580 "imagemin-gifsicle",
581 "imagemin-mozjpeg",
582 "imagemin-pngquant",
583 "imagemin-svgo",
584 ],
585 },
586 },
587 // Disable `loader`
588 loader: false,
589 }),
590 ],
591 },
592};
593```
594
595## Plugin Options
596
597- **[`test`](#test)**
598- **[`include`](#include)**
599- **[`exclude`](#exclude)**
600- **[`minimizer`](#minimizer)**
601- **[`generator`](#generator)**
602- **[`severityError`](#severityerror)**
603- **[`loader`](#loader)**
604- **[`concurrency`](#concurrency)**
605- **[`deleteOriginalAssets`](#deleteoriginalassets)**
606
607### `test`
608
609Type:
610
611```ts
612type test = string | RegExp | Array<string | RegExp>;
613```
614
615Default: `/\.(jpe?g\|png\|gif\|tif\|webp\|svg\|avif)\$/i`
616
617Test to match files against.
618
619**webpack.config.js**
620
621```js
622const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
623
624module.exports = {
625 optimization: {
626 minimizer: [
627 "...",
628 new ImageMinimizerPlugin({
629 test: /\.(jpe?g|png|gif|svg)$/i,
630 }),
631 ],
632 },
633};
634```
635
636### `include`
637
638Type:
639
640```ts
641type include = string | RegExp | Array<string | RegExp>;
642```
643
644Default: `undefined`
645
646Files to include.
647
648**webpack.config.js**
649
650```js
651const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
652
653module.exports = {
654 optimization: {
655 minimizer: [
656 "...",
657 new ImageMinimizerPlugin({
658 include: /\/includes/,
659 }),
660 ],
661 },
662};
663```
664
665### `exclude`
666
667Type:
668
669```ts
670type exclude = string | RegExp | Array<string | RegExp>;
671```
672
673Default: `undefined`
674
675Files to exclude.
676
677**webpack.config.js**
678
679```js
680const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
681
682module.exports = {
683 optimization: {
684 minimizer: [
685 "...",
686 new ImageMinimizerPlugin({
687 exclude: /\/excludes/,
688 }),
689 ],
690 },
691};
692```
693
694### `minimizer`
695
696Type:
697
698```ts
699type minimizer =
700 | {
701 implementation: (
702 original: {
703 filename: string;
704 data: Buffer;
705 warnings: Array<Error>;
706 errors: Array<Error>;
707 info: import("webpack").AssetInfo;
708 },
709 options?:
710 | {
711 [key: string]: any;
712 }
713 | undefined,
714 ) => Promise<{
715 filename: string;
716 data: Buffer;
717 warnings: Array<Error>;
718 errors: Array<Error>;
719 info: import("webpack").AssetInfo;
720 }> & {
721 setup?: (() => void) | undefined;
722 teardown?: (() => void) | undefined;
723 };
724 options?:
725 | {
726 [key: string]: any;
727 }
728 | undefined;
729 filter?: (source: Buffer, sourcePath: string) => boolean | undefined;
730 filename?:
731 | string
732 | ((
733 pathData: {
734 filename?: string | undefined;
735 },
736 assetInfo?: import("webpack").AssetInfo | undefined,
737 ) => string)
738 | undefined;
739 }
740 | Array<{
741 implementation: (
742 original: {
743 filename: string;
744 data: Buffer;
745 warnings: Array<Error>;
746 errors: Array<Error>;
747 info: import("webpack").AssetInfo;
748 },
749 options?:
750 | {
751 [key: string]: any;
752 }
753 | undefined,
754 ) => Promise<{
755 filename: string;
756 data: Buffer;
757 warnings: Array<Error>;
758 errors: Array<Error>;
759 info: import("webpack").AssetInfo;
760 }> & {
761 setup?: (() => void) | undefined;
762 teardown?: (() => void) | undefined;
763 };
764 options?:
765 | {
766 [key: string]: any;
767 }
768 | undefined;
769 filter?: (source: Buffer, sourcePath: string) => boolean | undefined;
770 filename?:
771 | string
772 | ((
773 pathData: {
774 filename?: string | undefined;
775 },
776 assetInfo?: import("webpack").AssetInfo | undefined,
777 ) => string)
778 | undefined;
779 }>;
780```
781
782Default: `undefined`
783
784Allows to setup default minify function.
785
786#### Available minimizers
787
788- `ImageMinimizerPlugin.imageminMinify`
789- **DEPRECATED** `ImageMinimizerPlugin.squooshMinify`
790- `ImageMinimizerPlugin.sharpMinify`
791- `ImageMinimizerPlugin.svgoMinify`
792
793#### Single minimizer example for `imagemin`
794
795**webpack.config.js**
796
797```js
798const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
799
800module.exports = {
801 optimization: {
802 minimizer: [
803 "...",
804 new ImageMinimizerPlugin({
805 minimizer: {
806 // Implementation
807 implementation: ImageMinimizerPlugin.imageminMinify,
808 // Options
809 options: {
810 plugins: [
811 "imagemin-gifsicle",
812 "imagemin-mozjpeg",
813 "imagemin-pngquant",
814 "imagemin-svgo",
815 ],
816 },
817 },
818 }),
819 ],
820 },
821};
822```
823
824More information and examples [here](https://github.com/imagemin/imagemin).
825
826#### **DEPRECATED** Single minimizer example for `squoosh`
827
828**webpack.config.js**
829
830```js
831const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
832
833module.exports = {
834 optimization: {
835 minimizer: [
836 "...",
837 new ImageMinimizerPlugin({
838 minimizer: {
839 // Implementation
840 implementation: ImageMinimizerPlugin.squooshMinify,
841 // Options
842 options: {
843 encodeOptions: {
844 mozjpeg: {
845 quality: 90,
846 },
847 },
848 },
849 },
850 }),
851 ],
852 },
853};
854```
855
856More information and examples [here](https://github.com/GoogleChromeLabs/squoosh/tree/dev/libsquoosh).
857
858#### Single minimizer example for `sharp`
859
860**webpack.config.js**
861
862```js
863const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
864
865module.exports = {
866 optimization: {
867 minimizer: [
868 "...",
869 new ImageMinimizerPlugin({
870 minimizer: {
871 // Implementation
872 implementation: ImageMinimizerPlugin.sharpMinify,
873 // Options
874 options: {
875 encodeOptions: {
876 jpeg: {
877 quality: 90,
878 },
879 },
880 },
881 },
882 }),
883 ],
884 },
885};
886```
887
888More information and examples [here](https://sharp.pixelplumbing.com/api-output#toformat).
889
890#### Single minimizer example for user defined implementation
891
892**webpack.config.js**
893
894```js
895const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
896
897module.exports = {
898 optimization: {
899 minimizer: [
900 "...",
901 new ImageMinimizerPlugin({
902 minimizer: {
903 implementation: async (original, options) => {
904 const inputExt = path.extname(original.filename).toLowerCase();
905
906 if (inputExt !== ".xxx") {
907 // Return `null` if the implementation does not support this file type
908 return null;
909 }
910
911 let result;
912
913 try {
914 result = await minifyAndReturnBuffer(original.data);
915 } catch (error) {
916 // Store error and return `null` if there was an error
917 original.errors.push(error);
918 return null;
919 }
920
921 return {
922 filename: original.filename,
923 data: result,
924 warnings: [...original.warnings],
925 errors: [...original.errors],
926 info: {
927 ...original.info,
928 // Please always set it to prevent double minification
929 minimized: true,
930 // Optional
931 minimizedBy: ["custom-name-of-minimication"],
932 },
933 };
934 },
935 options: {
936 // Custom options
937 },
938 },
939 }),
940 ],
941 },
942};
943```
944
945#### Multiple minimizers example
946
947Allows to setup multiple minimizers.
948
949**webpack.config.js**
950
951```js
952const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
953
954module.exports = {
955 optimization: {
956 minimizer: [
957 "...",
958 new ImageMinimizerPlugin({
959 minimizer: [
960 {
961 // `sharp` will handle all bitmap formats (JPG, PNG, GIF, ...)
962 implementation: ImageMinimizerPlugin.sharpMinify,
963
964 // exclude SVG if implementation support it. Not required for `sharp`.
965 // filter: (source, sourcePath) => !(/\.(svg)$/i.test(sourcePath)),
966
967 options: {
968 encodeOptions: {
969 // Your options for `sharp`
970 // https://sharp.pixelplumbing.com/api-output
971 },
972 },
973 },
974 {
975 // `svgo` will handle vector images (SVG)
976 implementation: ImageMinimizerPlugin.svgoMinify,
977 options: {
978 encodeOptions: {
979 // Pass over SVGs multiple times to ensure all optimizations are applied. False by default
980 multipass: true,
981 plugins: [
982 // set of built-in plugins enabled by default
983 // see: https://github.com/svg/svgo#default-preset
984 "preset-default",
985 ],
986 },
987 },
988 },
989 ],
990 }),
991 ],
992 },
993};
994```
995
996#### Minimizer options
997
998##### `implementation`
999
1000Type:
1001
1002```ts
1003type implementation = (
1004 original: {
1005 filename: string;
1006 data: Buffer;
1007 warnings: Array<Error>;
1008 errors: Array<Error>;
1009 info: import("webpack").AssetInfo;
1010 },
1011 options?: BasicTransformerOptions<T>,
1012) => Promise<{
1013 filename: string;
1014 data: Buffer;
1015 warnings: Array<Error>;
1016 errors: Array<Error>;
1017 info: import("webpack").AssetInfo;
1018}> & {
1019 setup?: (() => void) | undefined;
1020 teardown?: (() => void) | undefined;
1021};
1022```
1023
1024Default: `undefined`
1025
1026Configure the default `implementation`.
1027
1028**webpack.config.js**
1029
1030```js
1031const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1032
1033module.exports = {
1034 optimization: {
1035 minimizer: [
1036 "...",
1037 new ImageMinimizerPlugin({
1038 minimizer: {
1039 // Implementation
1040 implementation: ImageMinimizerPlugin.sharpMinify,
1041 // Options
1042 options: {
1043 encodeOptions: {
1044 jpeg: {
1045 quality: 90,
1046 },
1047 },
1048 },
1049 },
1050 }),
1051 ],
1052 },
1053};
1054```
1055
1056##### `options`
1057
1058Type:
1059
1060```ts
1061type options = {
1062 [key: string]: any;
1063};
1064```
1065
1066Default: `undefined`
1067
1068Options for the `implementation` option (i.e. options for `imagemin`/`squoosh`/`sharp`/custom implementation).
1069
1070**webpack.config.js**
1071
1072```js
1073const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1074
1075module.exports = {
1076 optimization: {
1077 minimizer: [
1078 "...",
1079 new ImageMinimizerPlugin({
1080 minimizer: {
1081 implementation: ImageMinimizerPlugin.sharpMinify,
1082 // Options
1083 options: {
1084 encodeOptions: {
1085 jpeg: {
1086 quality: 90,
1087 },
1088 },
1089 },
1090 },
1091 }),
1092 ],
1093 },
1094};
1095```
1096
1097##### `filter`
1098
1099Type:
1100
1101```ts
1102type filter = (source: Buffer, sourcePath: string) => boolean | undefined;
1103```
1104
1105Default: `() => true`
1106
1107Allows filtering of images for optimization/generation.
1108
1109Return `true` to optimize the image, `false` otherwise.
1110
1111**webpack.config.js**
1112
1113```js
1114const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1115
1116module.exports = {
1117 optimization: {
1118 minimizer: [
1119 "...",
1120 new ImageMinimizerPlugin({
1121 minimizer: {
1122 filter: (source, sourcePath) => {
1123 // The `source` argument is a `Buffer` of source file
1124 // The `sourcePath` argument is an absolute path to source
1125 if (source.byteLength < 8192) {
1126 return false;
1127 }
1128
1129 return true;
1130 },
1131 implementation: ImageMinimizerPlugin.imageminMinify,
1132 options: {
1133 plugins: [
1134 "imagemin-gifsicle",
1135 "imagemin-mozjpeg",
1136 "imagemin-pngquant",
1137 "imagemin-svgo",
1138 ],
1139 },
1140 },
1141 }),
1142 ],
1143 },
1144};
1145```
1146
1147##### `filename`
1148
1149Type:
1150
1151```ts
1152type filename =
1153 | string
1154 | ((
1155 pathData: {
1156 filename?: string | undefined;
1157 },
1158 assetInfo?: import("webpack").AssetInfo | undefined,
1159 ) => string)
1160 | undefined;
1161```
1162
1163Default: `undefined`
1164
1165Allows to set the filename.
1166Supported values see in [`webpack template strings`](https://webpack.js.org/configuration/output/#template-strings), `File-level` section.
1167
1168We also support `[width]` and `[height]` placeholders (only `sharp` and `squoosh`).
1169
1170**webpack.config.js**
1171
1172```js
1173const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1174
1175module.exports = {
1176 optimization: {
1177 minimizer: [
1178 "...",
1179 new ImageMinimizerPlugin({
1180 minimizer: {
1181 filename: "optimized-[name][ext]",
1182 implementation: ImageMinimizerPlugin.sharpMinify,
1183 // Options
1184 options: {
1185 encodeOptions: {
1186 jpeg: {
1187 quality: 90,
1188 },
1189 },
1190 },
1191 },
1192 }),
1193 ],
1194 },
1195};
1196```
1197
1198Example `function` usage:
1199
1200**webpack.config.js**
1201
1202```js
1203const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1204
1205module.exports = {
1206 optimization: {
1207 minimizer: [
1208 "...",
1209 new ImageMinimizerPlugin({
1210 minimizer: {
1211 filename: () => "optimized-[name][ext]",
1212 implementation: ImageMinimizerPlugin.sharpMinify,
1213 // Options
1214 options: {
1215 encodeOptions: {
1216 jpeg: {
1217 quality: 90,
1218 },
1219 },
1220 },
1221 },
1222 }),
1223 ],
1224 },
1225};
1226```
1227
1228### `generator`
1229
1230Type:
1231
1232```ts
1233type generator = Array<{
1234 implementation: (
1235 original: {
1236 filename: string;
1237 data: Buffer;
1238 warnings: Array<Error>;
1239 errors: Array<Error>;
1240 info: import("webpack").AssetInfo;
1241 },
1242 options?:
1243 | {
1244 [key: string]: any;
1245 }
1246 | undefined,
1247 ) => Promise<{
1248 filename: string;
1249 data: Buffer;
1250 warnings: Array<Error>;
1251 errors: Array<Error>;
1252 info: import("webpack").AssetInfo;
1253 }> & {
1254 setup?: (() => void) | undefined;
1255 teardown?: (() => void) | undefined;
1256 };
1257 options?:
1258 | {
1259 [key: string]: any;
1260 }
1261 | undefined;
1262 filter?: (source: Buffer, sourcePath: string) => boolean | undefined;
1263 filename?:
1264 | string
1265 | ((
1266 pathData: {
1267 filename?: string | undefined;
1268 },
1269 assetInfo?: import("webpack").AssetInfo | undefined,
1270 ) => string)
1271 | undefined;
1272 preset?: string | undefined;
1273 type?: "import" | "asset" | undefined;
1274}>;
1275```
1276
1277Default: `undefined`
1278
1279Allow to setup default generators.
1280Useful if you need generate `webp`/`avif`/etc from other formats.
1281
1282> **Warning**
1283>
1284> 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.
1285
1286> **Warning**
1287>
1288> The option will not work if you disable `loader` (i.e. set the `loader` option to `false`).
1289
1290#### Available generators
1291
1292- `ImageMinimizerPlugin.imageminGenerate`
1293- **DEPRECATED** `ImageMinimizerPlugin.squooshGenerate`
1294- `ImageMinimizerPlugin.sharpGenerate`
1295
1296#### Generator example for `imagemin`
1297
1298Example `webp` generator:
1299
1300**webpack.config.js**
1301
1302```js
1303const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1304
1305module.exports = {
1306 optimization: {
1307 minimizer: [
1308 "...",
1309 new ImageMinimizerPlugin({
1310 generator: [
1311 {
1312 // You can apply generator using `?as=webp`, you can use any name and provide more options
1313 preset: "webp",
1314 implementation: ImageMinimizerPlugin.imageminGenerate,
1315 options: {
1316 // Please specify only one plugin here, multiple plugins will not work
1317 plugins: ["imagemin-webp"],
1318 },
1319 },
1320 ],
1321 }),
1322 ],
1323 },
1324};
1325```
1326
1327#### **DEPRECATED** Generator example for `squoosh`
1328
1329**webpack.config.js**
1330
1331```js
1332const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1333
1334module.exports = {
1335 optimization: {
1336 minimizer: [
1337 "...",
1338 new ImageMinimizerPlugin({
1339 generator: [
1340 {
1341 // You can apply generator using `?as=webp`, you can use any name and provide more options
1342 preset: "webp",
1343 implementation: ImageMinimizerPlugin.squooshGenerate,
1344 options: {
1345 encodeOptions: {
1346 // Please specify only one codec here, multiple codecs will not work
1347 webp: {
1348 quality: 90,
1349 },
1350 },
1351 },
1352 },
1353 ],
1354 }),
1355 ],
1356 },
1357};
1358```
1359
1360#### Generator example for `sharp`
1361
1362**webpack.config.js**
1363
1364```js
1365const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1366
1367module.exports = {
1368 optimization: {
1369 minimizer: [
1370 "...",
1371 new ImageMinimizerPlugin({
1372 generator: [
1373 {
1374 // You can apply generator using `?as=webp`, you can use any name and provide more options
1375 preset: "webp",
1376 implementation: ImageMinimizerPlugin.sharpGenerate,
1377 options: {
1378 encodeOptions: {
1379 // Please specify only one codec here, multiple codecs will not work
1380 webp: {
1381 quality: 90,
1382 },
1383 },
1384 },
1385 },
1386 ],
1387 }),
1388 ],
1389 },
1390};
1391```
1392
1393Now you can generate the new image using:
1394
1395```js
1396// Old approach for getting URL
1397import webp from "./file.jpg?as=webp";
1398
1399// Assets modules
1400console.log(new URL("./file.jpg?as=webp"));
1401```
1402
1403```css
1404div {
1405 background: url("./file.jpg?as=webp");
1406}
1407```
1408
1409You can use `?as=webp` in any type of files.
1410
1411Example multiple generators:
1412
1413**webpack.config.js**
1414
1415```js
1416const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1417
1418module.exports = {
1419 optimization: {
1420 minimizer: [
1421 "...",
1422 new ImageMinimizerPlugin({
1423 generator: [
1424 {
1425 // You can apply generator using `?as=webp`, you can use any name and provide more options
1426 preset: "webp",
1427 implementation: ImageMinimizerPlugin.sharpGenerate,
1428 options: {
1429 encodeOptions: {
1430 webp: {
1431 lossless: false,
1432 },
1433 },
1434 },
1435 },
1436 {
1437 // You can apply generator using `?as=avif`, you can use any name and provide more options
1438 preset: "avif",
1439 implementation: ImageMinimizerPlugin.sharpGenerate,
1440 options: {
1441 encodeOptions: {
1442 avif: {
1443 lossless: false,
1444 },
1445 },
1446 },
1447 },
1448 ],
1449 }),
1450 ],
1451 },
1452};
1453```
1454
1455`squoosh` and `sharp` generator supports more options, for example you can resize an image:
1456
1457**webpack.config.js**
1458
1459```js
1460const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1461
1462module.exports = {
1463 optimization: {
1464 minimizer: [
1465 "...",
1466 new ImageMinimizerPlugin({
1467 generator: [
1468 {
1469 // You can apply generator using `?as=webp-100-50`, you can use any name and provide more options
1470 preset: "webp-100-50",
1471 // implementation: ImageMinimizerPlugin.squooshGenerate,
1472 implementation: ImageMinimizerPlugin.sharpGenerate,
1473 options: {
1474 resize: {
1475 enabled: true,
1476 width: 100,
1477 height: 50,
1478 },
1479 encodeOptions: {
1480 webp: {
1481 quality: 90,
1482 },
1483 },
1484 },
1485 },
1486 ],
1487 }),
1488 ],
1489 },
1490};
1491```
1492
1493You can find more information [here](https://github.com/GoogleChromeLabs/squoosh/tree/dev/libsquoosh).
1494
1495#### Generator example for user defined implementation
1496
1497You can use your own generator implementation.
1498
1499**webpack.config.js**
1500
1501```js
1502const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1503
1504module.exports = {
1505 optimization: {
1506 minimizer: [
1507 "...",
1508 new ImageMinimizerPlugin({
1509 generator: [
1510 {
1511 // You can apply generator using `?as=webp`, you can use any name and provide more options
1512 preset: "webp",
1513 implementation: async (original, options) => {
1514 const inputExt = path.extname(original.filename).toLowerCase();
1515
1516 if (inputExt !== ".xxx") {
1517 // Store error and return `null` if the implementation does not support this file type
1518 original.errors.push(error);
1519 return null;
1520 }
1521
1522 let result;
1523
1524 try {
1525 result = await minifyAndReturnBuffer(original.data);
1526 } catch (error) {
1527 // Store error and return `null` if there was an error
1528 original.errors.push(error);
1529 return null;
1530 }
1531
1532 return {
1533 filename: original.filename,
1534 data: result,
1535 warnings: [...original.warnings],
1536 errors: [...original.errors],
1537 info: {
1538 ...original.info,
1539 // Please always set it to prevent double minification
1540 generated: true,
1541 // Optional
1542 generatedBy: ["custom-name-of-minification"],
1543 },
1544 };
1545 },
1546 options: {
1547 // Your options
1548 },
1549 },
1550 ],
1551 }),
1552 ],
1553 },
1554};
1555```
1556
1557#### Generator options
1558
1559##### `type`
1560
1561Type:
1562
1563```ts
1564type type = "import" | "asset" | undefined;
1565```
1566
1567Default: `"import"`
1568
1569Allows you to apply the generator for `import` or assets from compilation (useful for copied assets).
1570By 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.
1571
1572**webpack.config.js**
1573
1574```js
1575const CopyPlugin = require("copy-webpack-plugin");
1576const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1577
1578module.exports = {
1579 optimization: {
1580 minimizer: [
1581 "...",
1582 new ImageMinimizerPlugin({
1583 minimizer: {
1584 implementation: ImageMinimizerPlugin.imageminMinify,
1585 options: {
1586 plugins: [
1587 "imagemin-gifsicle",
1588 "imagemin-mozjpeg",
1589 "imagemin-pngquant",
1590 "imagemin-svgo",
1591 ],
1592 },
1593 },
1594 generator: [
1595 {
1596 // Apply generator for copied assets
1597 type: "asset",
1598 // You can use `ImageMinimizerPlugin.squooshGenerate`
1599 // You can use `ImageMinimizerPlugin.sharpGenerate`
1600 implementation: ImageMinimizerPlugin.imageminGenerate,
1601 options: {
1602 plugins: ["imagemin-webp"],
1603 },
1604 },
1605 ],
1606 }),
1607 ],
1608 },
1609 plugins: [new CopyPlugin({ patterns: ["images/**/*.png"] })],
1610};
1611```
1612
1613##### `preset`
1614
1615Type:
1616
1617```ts
1618type preset = string | undefined;
1619```
1620
1621Default: `undefined`
1622
1623Configure the name of preset, i.e. you can use it in `?as=name`.
1624
1625**webpack.config.js**
1626
1627```js
1628const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1629
1630module.exports = {
1631 optimization: {
1632 minimizer: [
1633 "...",
1634 new ImageMinimizerPlugin({
1635 generator: [
1636 {
1637 preset: "name",
1638 // Implementation
1639 implementation: ImageMinimizerPlugin.sharpMinify,
1640 options: {
1641 encodeOptions: {
1642 jpeg: {
1643 quality: 85,
1644 },
1645 },
1646 },
1647 },
1648 ],
1649 }),
1650 ],
1651 },
1652};
1653```
1654
1655##### `implementation`
1656
1657Type:
1658
1659```ts
1660type implementation = (
1661 original: {
1662 filename: string;
1663 data: Buffer;
1664 warnings: Array<Error>;
1665 errors: Array<Error>;
1666 info: import("webpack").AssetInfo;
1667 },
1668 options?:
1669 | {
1670 [key: string]: any;
1671 }
1672 | undefined,
1673) => Promise<{
1674 filename: string;
1675 data: Buffer;
1676 warnings: Array<Error>;
1677 errors: Array<Error>;
1678 info: import("webpack").AssetInfo;
1679}> & {
1680 setup?: (() => void) | undefined;
1681 teardown?: (() => void) | undefined;
1682};
1683```
1684
1685Default: `undefined`
1686
1687Configure the default `implementation`.
1688
1689**webpack.config.js**
1690
1691```js
1692const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1693
1694module.exports = {
1695 optimization: {
1696 minimizer: [
1697 "...",
1698 new ImageMinimizerPlugin({
1699 generator: [
1700 {
1701 preset: "name",
1702 // Implementation
1703 implementation: ImageMinimizerPlugin.sharpMinify,
1704 options: {
1705 encodeOptions: {
1706 jpeg: {
1707 quality: 85,
1708 },
1709 },
1710 },
1711 },
1712 ],
1713 }),
1714 ],
1715 },
1716};
1717```
1718
1719##### `options`
1720
1721Type:
1722
1723```ts
1724type options = {
1725 [key: string]: any;
1726};
1727```
1728
1729Default: `undefined`
1730
1731Options for the `implementation` option (i.e. options for `imagemin`/`squoosh`/`sharp`/custom implementation).
1732
1733**webpack.config.js**
1734
1735```js
1736const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1737
1738module.exports = {
1739 optimization: {
1740 minimizer: [
1741 "...",
1742 new ImageMinimizerPlugin({
1743 generator: [
1744 {
1745 preset: "name",
1746 implementation: ImageMinimizerPlugin.sharpMinify,
1747 // Options
1748 options: {
1749 encodeOptions: {
1750 jpeg: {
1751 quality: 90,
1752 },
1753 },
1754 },
1755 },
1756 ],
1757 }),
1758 ],
1759 },
1760};
1761```
1762
1763##### `filter`
1764
1765Type:
1766
1767```ts
1768type filter = (source: Buffer, sourcePath: string) => boolean;
1769```
1770
1771Default: `() => true`
1772
1773Allows filtering of images for optimization/generation.
1774
1775Return `true` to optimize the image, `false` otherwise.
1776
1777**webpack.config.js**
1778
1779```js
1780const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1781
1782module.exports = {
1783 optimization: {
1784 minimizer: [
1785 "...",
1786 new ImageMinimizerPlugin({
1787 generator: [
1788 {
1789 preset: "name",
1790 filter: (source, sourcePath) => {
1791 // The `source` argument is a `Buffer` of source file
1792 // The `sourcePath` argument is an absolute path to source
1793 if (source.byteLength < 8192) {
1794 return false;
1795 }
1796
1797 return true;
1798 },
1799 implementation: ImageMinimizerPlugin.imageminMinify,
1800 options: {
1801 plugins: [
1802 "imagemin-gifsicle",
1803 "imagemin-mozjpeg",
1804 "imagemin-pngquant",
1805 "imagemin-svgo",
1806 ],
1807 },
1808 },
1809 ],
1810 }),
1811 ],
1812 },
1813};
1814```
1815
1816##### `filename`
1817
1818Type:
1819
1820```ts
1821type filename =
1822 | string
1823 | ((
1824 pathData: PathData,
1825 assetInfo?: import("webpack").AssetInfo | undefined,
1826 ) => string);
1827```
1828
1829Default: `undefined`
1830
1831Allows to set the filename.
1832Supported values see in [`webpack template strings`](https://webpack.js.org/configuration/output/#template-strings), `File-level` section.
1833
1834**webpack.config.js**
1835
1836```js
1837const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1838
1839module.exports = {
1840 optimization: {
1841 minimizer: [
1842 "...",
1843 new ImageMinimizerPlugin({
1844 generator: [
1845 {
1846 preset: "name",
1847 filename: "generated-[name][ext]",
1848 implementation: ImageMinimizerPlugin.sharpMinify,
1849 // Options
1850 options: {
1851 encodeOptions: {
1852 jpeg: {
1853 quality: 90,
1854 },
1855 },
1856 },
1857 },
1858 ],
1859 }),
1860 ],
1861 },
1862};
1863```
1864
1865Example of `function` usage:
1866
1867**webpack.config.js**
1868
1869```js
1870const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1871
1872module.exports = {
1873 optimization: {
1874 minimizer: [
1875 "...",
1876 new ImageMinimizerPlugin({
1877 generator: [
1878 {
1879 preset: "name",
1880 filename: () => "generated-[name][ext]",
1881 implementation: ImageMinimizerPlugin.sharpMinify,
1882 // Options
1883 options: {
1884 encodeOptions: {
1885 jpeg: {
1886 quality: 90,
1887 },
1888 },
1889 },
1890 },
1891 ],
1892 }),
1893 ],
1894 },
1895};
1896```
1897
1898### `severityError`
1899
1900Type:
1901
1902```ts
1903type severityError = string;
1904```
1905
1906Default: `'error'`
1907
1908Allows to choose how errors are displayed.
1909
1910Сan have the following values:
1911
1912- `'off'` - suppresses errors and warnings
1913- `'warning'` - emit warnings instead errors
1914- `'error'` - emit errors
1915
1916**webpack.config.js**
1917
1918```js
1919const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1920
1921module.exports = {
1922 optimization: {
1923 minimizer: [
1924 "...",
1925 new ImageMinimizerPlugin({
1926 severityError: "warning",
1927 minimizer: {
1928 implementation: ImageMinimizerPlugin.imageminMinify,
1929 options: {
1930 plugins: [
1931 "imagemin-gifsicle",
1932 "imagemin-mozjpeg",
1933 "imagemin-pngquant",
1934 "imagemin-svgo",
1935 ],
1936 },
1937 },
1938 }),
1939 ],
1940 },
1941};
1942```
1943
1944### `loader`
1945
1946Type:
1947
1948```ts
1949type loader = boolean;
1950```
1951
1952Default: `true`
1953
1954Automatically adding built-in `loader`, used to optimize/generate images.
1955
1956**webpack.config.js**
1957
1958```js
1959const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1960
1961module.exports = {
1962 optimization: {
1963 minimizer: [
1964 "...",
1965 new ImageMinimizerPlugin({
1966 loader: false,
1967 // `generator` will not work in this case
1968 minimizer: {
1969 implementation: ImageMinimizerPlugin.imageminMinify,
1970 options: {
1971 plugins: [
1972 "imagemin-gifsicle",
1973 "imagemin-mozjpeg",
1974 "imagemin-pngquant",
1975 "imagemin-svgo",
1976 ],
1977 },
1978 },
1979 }),
1980 ],
1981 },
1982};
1983```
1984
1985### `concurrency`
1986
1987Type:
1988
1989```ts
1990type concurrency = number;
1991```
1992
1993Default: `Math.max(1, os.cpus().length - 1)`
1994
1995Maximum number of concurrency optimization processes in one time.
1996
1997**webpack.config.js**
1998
1999```js
2000const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2001
2002module.exports = {
2003 optimization: {
2004 minimizer: [
2005 "...",
2006 new ImageMinimizerPlugin({
2007 concurrency: 3,
2008 minimizer: {
2009 implementation: ImageMinimizerPlugin.imageminMinify,
2010 options: {
2011 plugins: [
2012 "imagemin-gifsicle",
2013 "imagemin-mozjpeg",
2014 "imagemin-pngquant",
2015 "imagemin-svgo",
2016 ],
2017 },
2018 },
2019 }),
2020 ],
2021 },
2022};
2023```
2024
2025### `deleteOriginalAssets`
2026
2027Type:
2028
2029```ts
2030type deleteOriginalAssets = boolean;
2031```
2032
2033Default: `true`
2034
2035Allows removing original assets after optimization.
2036
2037**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.**
2038
2039**webpack.config.js**
2040
2041```js
2042const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2043
2044module.exports = {
2045 optimization: {
2046 minimizer: [
2047 "...",
2048 new ImageMinimizerPlugin({
2049 // Disable loader
2050 loader: false,
2051 // Allows to keep original asset and minimized assets with different filenames
2052 deleteOriginalAssets: false,
2053 minimizer: {
2054 filename: "[path][name].webp",
2055 implementation: ImageMinimizerPlugin.imageminMinify,
2056 options: {
2057 plugins: [
2058 "imagemin-gifsicle",
2059 "imagemin-mozjpeg",
2060 "imagemin-pngquant",
2061 "imagemin-svgo",
2062 ],
2063 },
2064 },
2065 }),
2066 ],
2067 },
2068};
2069```
2070
2071## Loader Options
2072
2073- **[`minimizer`](#minimizer-1)**
2074- **[`generator`](#generator-1)**
2075- **[`severityError`](severityerror-1)**
2076
2077### `minimizer`
2078
2079Type:
2080
2081```ts
2082type minimizer =
2083 | {
2084 implementation: (
2085 original: {
2086 filename: string;
2087 data: Buffer;
2088 warnings: Array<Error>;
2089 errors: Array<Error>;
2090 info: import("webpack").AssetInfo;
2091 },
2092 options?:
2093 | {
2094 [key: string]: any;
2095 }
2096 | undefined,
2097 ) => Promise<{
2098 filename: string;
2099 data: Buffer;
2100 warnings: Array<Error>;
2101 errors: Array<Error>;
2102 info: import("webpack").AssetInfo;
2103 }> & {
2104 setup?: (() => void) | undefined;
2105 teardown?: (() => void) | undefined;
2106 };
2107 options?:
2108 | {
2109 [key: string]: any;
2110 }
2111 | undefined;
2112 filter?: (source: Buffer, sourcePath: string) => boolean | undefined;
2113 filename?:
2114 | string
2115 | ((
2116 pathData: {
2117 filename?: string | undefined;
2118 },
2119 assetInfo?: import("webpack").AssetInfo | undefined,
2120 ) => string)
2121 | undefined;
2122 }
2123 | Array<{
2124 implementation: (
2125 original: {
2126 filename: string;
2127 data: Buffer;
2128 warnings: Array<Error>;
2129 errors: Array<Error>;
2130 info: import("webpack").AssetInfo;
2131 },
2132 options?:
2133 | {
2134 [key: string]: any;
2135 }
2136 | undefined,
2137 ) => Promise<{
2138 filename: string;
2139 data: Buffer;
2140 warnings: Array<Error>;
2141 errors: Array<Error>;
2142 info: import("webpack").AssetInfo;
2143 }> & {
2144 setup?: (() => void) | undefined;
2145 teardown?: (() => void) | undefined;
2146 };
2147 options?:
2148 | {
2149 [key: string]: any;
2150 }
2151 | undefined;
2152 filter?: (source: Buffer, sourcePath: string) => boolean | undefined;
2153 filename?:
2154 | string
2155 | ((
2156 pathData: {
2157 filename?: string | undefined;
2158 },
2159 assetInfo?: import("webpack").AssetInfo | undefined,
2160 ) => string)
2161 | undefined;
2162 }>;
2163```
2164
2165Default: `undefined`
2166
2167Allows to setup default minimizer.
2168
2169#### Loader minimizer example for `imagemin`
2170
2171**webpack.config.js**
2172
2173```js
2174const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2175
2176module.exports = {
2177 module: {
2178 rules: [
2179 {
2180 test: /\.(jpe?g|png|gif|svg)$/i,
2181 type: "asset",
2182 },
2183 {
2184 test: /\.(jpe?g|png|gif|svg)$/i,
2185 loader: ImageMinimizerPlugin.loader,
2186 enforce: "pre",
2187 options: {
2188 minimizer: {
2189 implementation: ImageMinimizerPlugin.imageminMinify,
2190 options: {
2191 plugins: [
2192 "imagemin-gifsicle",
2193 "imagemin-mozjpeg",
2194 "imagemin-pngquant",
2195 "imagemin-svgo",
2196 ],
2197 },
2198 },
2199 },
2200 },
2201 ],
2202 },
2203};
2204```
2205
2206For more information and supported options please read [here](#minimizer).
2207
2208### `generator`
2209
2210Type:
2211
2212```ts
2213type generator = Array<{
2214 implementation: TransformerFunction<T>;
2215 options?: BasicTransformerOptions<T>;
2216 filter?: FilterFn | undefined;
2217 filename?: string | FilenameFn | undefined;
2218 preset?: string | undefined;
2219 type?: "import" | "asset" | undefined;
2220}>;
2221```
2222
2223Default: `undefined`
2224
2225Allow to setup default generators.
2226Useful if you need generate `webp`/`avif`/etc from other formats.
2227
2228#### Loader generator example for `imagemin`
2229
2230**webpack.config.js**
2231
2232```js
2233const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2234
2235module.exports = {
2236 module: {
2237 rules: [
2238 {
2239 test: /\.(jpe?g|png|gif|svg)$/i,
2240 type: "asset",
2241 },
2242 {
2243 test: /\.(jpe?g|png|gif|svg)$/i,
2244 loader: ImageMinimizerPlugin.loader,
2245 enforce: "pre",
2246 options: {
2247 generator: [
2248 {
2249 preset: "webp",
2250 implementation: ImageMinimizerPlugin.imageminGenerate,
2251 options: {
2252 plugins: ["imagemin-webp"],
2253 },
2254 },
2255 ],
2256 },
2257 },
2258 ],
2259 },
2260};
2261```
2262
2263For more information and supported options please read [here](#generator).
2264
2265### `severityError`
2266
2267Type:
2268
2269```ts
2270type severityError = string;
2271```
2272
2273Default: `'error'`
2274
2275Allows to choose how errors are displayed.
2276
2277Сan have the following values:
2278
2279- `'off'` - suppresses errors and warnings
2280- `'warning'` - emit warnings instead errors
2281- `'error'` - emit errors
2282
2283**webpack.config.js**
2284
2285```js
2286const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2287
2288module.exports = {
2289 module: {
2290 rules: [
2291 {
2292 test: /\.(jpe?g|png|gif|svg)$/i,
2293 type: "asset",
2294 },
2295 {
2296 test: /\.(jpe?g|png|gif|svg)$/i,
2297 use: [
2298 {
2299 loader: ImageMinimizerPlugin.loader,
2300 options: {
2301 severityError: "warning",
2302 minimizerOptions: {
2303 plugins: ["gifsicle"],
2304 },
2305 },
2306 },
2307 ],
2308 },
2309 ],
2310 },
2311};
2312```
2313
2314## Additional API
2315
2316### `imageminNormalizeConfig(config)`
2317
2318The function normalizes configuration (converts plugins names and options to `Function`s) for using in `imagemin` package directly.
2319
2320```js
2321const imagemin = require("imagemin");
2322const { imageminNormalizeConfig } = require("image-minimizer-webpack-plugin");
2323
2324/*
2325 console.log(imageminConfig);
2326 =>
2327 {
2328 plugins: [Function, Function],
2329 pluginsMeta: [
2330 { name: "imagemin-jpegtran", version: "x.x.x", options: {} },
2331 { name: "imagemin-pngquant", version: "x.x.x", options: { quality: [0.6, 0.8] }
2332 ]
2333 }
2334*/
2335
2336(async () => {
2337 const imageminConfig = await imageminNormalizeConfig({
2338 plugins: ["jpegtran", ["pngquant", { quality: [0.6, 0.8] }]],
2339 });
2340 const files = await imagemin(["images/*.{jpg,png}"], {
2341 destination: "build/images",
2342 plugins: imageminConfig.plugins,
2343 });
2344
2345 console.log(files);
2346 // => [{data: <Buffer 89 50 4e …>, path: 'build/images/foo.jpg'}, …]
2347})();
2348```
2349
2350## Examples
2351
2352### Optimize images based on size
2353
2354You can use difference options (like `progressive`/`interlaced`/etc.) based on image size (example - don't do progressive transformation for small images).
2355
2356What is `progressive` image? [`Answer here`](https://jmperezperez.com/medium-image-progressive-loading-placeholder/).
2357
2358**webpack.config.js**
2359
2360```js
2361const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2362
2363module.exports = {
2364 optimization: {
2365 minimizer: [
2366 new ImageMinimizerPlugin({
2367 minimizer: {
2368 implementation: ImageMinimizerPlugin.imageminMinify,
2369 options: {
2370 plugins: [["jpegtran", { progressive: true }]],
2371 },
2372 // Only apply this one to files equal to or over 8192 bytes
2373 filter: (source) => {
2374 if (source.byteLength >= 8192) {
2375 return true;
2376 }
2377
2378 return false;
2379 },
2380 },
2381 }),
2382 new ImageMinimizerPlugin({
2383 minimizer: {
2384 implementation: ImageMinimizerPlugin.imageminMinify,
2385 options: {
2386 plugins: [["jpegtran", { progressive: false }]],
2387 },
2388 // Only apply this one to files under 8192
2389 filter: (source) => {
2390 if (source.byteLength < 8192) {
2391 return true;
2392 }
2393
2394 return false;
2395 },
2396 },
2397 }),
2398 ],
2399 },
2400};
2401```
2402
2403### Optimize and generate `webp` images
2404
2405- imagemin
2406
2407**webpack.config.js**
2408
2409```js
2410const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2411
2412module.exports = {
2413 optimization: {
2414 minimizer: [
2415 "...",
2416 new ImageMinimizerPlugin({
2417 minimizer: {
2418 implementation: ImageMinimizerPlugin.imageminMinify,
2419 options: {
2420 plugins: [
2421 "imagemin-gifsicle",
2422 "imagemin-mozjpeg",
2423 "imagemin-pngquant",
2424 "imagemin-svgo",
2425 ],
2426 },
2427 },
2428 generator: [
2429 {
2430 // You can apply generator using `?as=webp`, you can use any name and provide more options
2431 preset: "webp",
2432 implementation: ImageMinimizerPlugin.imageminGenerate,
2433 options: {
2434 plugins: ["imagemin-webp"],
2435 },
2436 },
2437 ],
2438 }),
2439 ],
2440 },
2441};
2442```
2443
2444- **DEPRECATED** squoosh
2445
2446**webpack.config.js**
2447
2448```js
2449const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2450
2451module.exports = {
2452 optimization: {
2453 minimizer: [
2454 "...",
2455 new ImageMinimizerPlugin({
2456 minimizer: {
2457 implementation: ImageMinimizerPlugin.squooshMinify,
2458 },
2459 generator: [
2460 {
2461 // You can apply generator using `?as=webp`, you can use any name and provide more options
2462 preset: "webp",
2463 implementation: ImageMinimizerPlugin.squooshGenerate,
2464 options: {
2465 encodeOptions: {
2466 webp: {
2467 quality: 90,
2468 },
2469 },
2470 },
2471 },
2472 ],
2473 }),
2474 ],
2475 },
2476};
2477```
2478
2479- sharp
2480
2481**webpack.config.js**
2482
2483```js
2484const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2485
2486module.exports = {
2487 optimization: {
2488 minimizer: [
2489 "...",
2490 new ImageMinimizerPlugin({
2491 minimizer: {
2492 implementation: ImageMinimizerPlugin.sharpMinify,
2493 },
2494 generator: [
2495 {
2496 // You can apply generator using `?as=webp`, you can use any name and provide more options
2497 preset: "webp",
2498 implementation: ImageMinimizerPlugin.sharpGenerate,
2499 options: {
2500 encodeOptions: {
2501 webp: {
2502 quality: 90,
2503 },
2504 },
2505 },
2506 },
2507 ],
2508 }),
2509 ],
2510 },
2511};
2512```
2513
2514### Generate `webp` images from copied assets
2515
2516- imagemin
2517
2518**webpack.config.js**
2519
2520```js
2521const CopyPlugin = require("copy-webpack-plugin");
2522const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2523
2524module.exports = {
2525 optimization: {
2526 minimizer: [
2527 "...",
2528 new ImageMinimizerPlugin({
2529 minimizer: {
2530 implementation: ImageMinimizerPlugin.imageminMinify,
2531 options: {
2532 plugins: [
2533 "imagemin-gifsicle",
2534 "imagemin-mozjpeg",
2535 "imagemin-pngquant",
2536 "imagemin-svgo",
2537 ],
2538 },
2539 },
2540 generator: [
2541 {
2542 type: "asset",
2543 implementation: ImageMinimizerPlugin.imageminGenerate,
2544 options: {
2545 plugins: ["imagemin-webp"],
2546 },
2547 },
2548 ],
2549 }),
2550 ],
2551 },
2552 plugins: [new CopyPlugin({ patterns: ["images/**/*.png"] })],
2553};
2554```
2555
2556- **DEPRECATED** squoosh
2557
2558**webpack.config.js**
2559
2560```js
2561const CopyPlugin = require("copy-webpack-plugin");
2562const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2563
2564module.exports = {
2565 optimization: {
2566 minimizer: [
2567 "...",
2568 new ImageMinimizerPlugin({
2569 minimizer: {
2570 implementation: ImageMinimizerPlugin.squooshMinify,
2571 },
2572 generator: [
2573 {
2574 type: "asset",
2575 implementation: ImageMinimizerPlugin.squooshGenerate,
2576 options: {
2577 encodeOptions: {
2578 webp: {
2579 quality: 90,
2580 },
2581 },
2582 },
2583 },
2584 ],
2585 }),
2586 ],
2587 },
2588 plugins: [new CopyPlugin({ patterns: ["images/**/*.png"] })],
2589};
2590```
2591
2592- sharp
2593
2594**webpack.config.js**
2595
2596```js
2597const CopyPlugin = require("copy-webpack-plugin");
2598const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2599
2600module.exports = {
2601 optimization: {
2602 minimizer: [
2603 "...",
2604 new ImageMinimizerPlugin({
2605 minimizer: {
2606 implementation: ImageMinimizerPlugin.sharpMinify,
2607 },
2608 generator: [
2609 {
2610 type: "asset",
2611 implementation: ImageMinimizerPlugin.sharpGenerate,
2612 options: {
2613 encodeOptions: {
2614 webp: {
2615 quality: 90,
2616 },
2617 },
2618 },
2619 },
2620 ],
2621 }),
2622 ],
2623 },
2624 plugins: [new CopyPlugin({ patterns: ["images/**/*.png"] })],
2625};
2626```
2627
2628## Contributing
2629
2630Please take a moment to read our contributing guidelines if you haven't yet done so.
2631
2632[CONTRIBUTING](./.github/CONTRIBUTING.md)
2633
2634## License
2635
2636[MIT](./LICENSE)
2637
2638[npm]: https://img.shields.io/npm/v/image-minimizer-webpack-plugin.svg
2639[npm-url]: https://npmjs.com/package/image-minimizer-webpack-plugin
2640[node]: https://img.shields.io/node/v/image-minimizer-webpack-plugin.svg
2641[node-url]: https://nodejs.org
2642[tests]: https://github.com/webpack-contrib/image-minimizer-webpack-plugin/workflows/image-minimizer-webpack-plugin/badge.svg
2643[tests-url]: https://github.com/webpack-contrib/image-minimizer-webpack-plugin/actions
2644[cover]: https://codecov.io/gh/webpack-contrib/image-minimizer-webpack-plugin/branch/master/graph/badge.svg
2645[cover-url]: https://codecov.io/gh/webpack-contrib/image-minimizer-webpack-plugin
2646[discussion]: https://img.shields.io/github/discussions/webpack/webpack
2647[discussion-url]: https://github.com/webpack/webpack/discussions
2648[size]: https://packagephobia.now.sh/badge?p=image-minimizer-webpack-plugin
2649[size-url]: https://packagephobia.now.sh/result?p=image-minimizer-webpack-plugin