UNPKG

63 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[![chat][chat]][chat-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 - [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 - [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 - [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- [`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- [`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### 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.squooshMinify,
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- `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#### 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)$/i, // exclude SVG if implementation support it. Not required for `sharp`.
965
966 options: {
967 encodeOptions: {
968 // Your options for `sharp`
969 // https://sharp.pixelplumbing.com/api-output
970 },
971 },
972 },
973 {
974 // `svgo` will handle vector images (SVG)
975 implementation: ImageMinimizerPlugin.svgoMinify,
976 options: {
977 encodeOptions: {
978 // Pass over SVGs multiple times to ensure all optimizations are applied. False by default
979 multipass: true,
980 plugins: [
981 // set of built-in plugins enabled by default
982 // see: https://github.com/svg/svgo#default-preset
983 "preset-default",
984 ],
985 },
986 },
987 },
988 ],
989 }),
990 ],
991 },
992};
993```
994
995#### Minimizer options
996
997##### `implementation`
998
999Type:
1000
1001```ts
1002type implementation = (
1003 original: {
1004 filename: string;
1005 data: Buffer;
1006 warnings: Array<Error>;
1007 errors: Array<Error>;
1008 info: import("webpack").AssetInfo;
1009 },
1010 options?: BasicTransformerOptions<T>
1011) => Promise<{
1012 filename: string;
1013 data: Buffer;
1014 warnings: Array<Error>;
1015 errors: Array<Error>;
1016 info: import("webpack").AssetInfo;
1017}> & {
1018 setup?: (() => void) | undefined;
1019 teardown?: (() => void) | undefined;
1020};
1021```
1022
1023Default: `undefined`
1024
1025Configure the default `implementation`.
1026
1027**webpack.config.js**
1028
1029```js
1030const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1031
1032module.exports = {
1033 optimization: {
1034 minimizer: [
1035 "...",
1036 new ImageMinimizerPlugin({
1037 minimizer: {
1038 // Implementation
1039 implementation: ImageMinimizerPlugin.squooshMinify,
1040 },
1041 }),
1042 ],
1043 },
1044};
1045```
1046
1047##### `options`
1048
1049Type:
1050
1051```ts
1052type options = {
1053 [key: string]: any;
1054};
1055```
1056
1057Default: `undefined`
1058
1059Options for the `implementation` option (i.e. options for `imagemin`/`squoosh`/`sharp`/custom implementation).
1060
1061**webpack.config.js**
1062
1063```js
1064const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1065
1066module.exports = {
1067 optimization: {
1068 minimizer: [
1069 "...",
1070 new ImageMinimizerPlugin({
1071 minimizer: {
1072 implementation: ImageMinimizerPlugin.squooshMinify,
1073 // Options
1074 options: {
1075 encodeOptions: {
1076 mozjpeg: {
1077 quality: 90,
1078 },
1079 },
1080 },
1081 },
1082 }),
1083 ],
1084 },
1085};
1086```
1087
1088##### `filter`
1089
1090Type:
1091
1092```ts
1093type filter = (source: Buffer, sourcePath: string) => boolean | undefined;
1094```
1095
1096Default: `() => true`
1097
1098Allows filtering of images for optimization/generation.
1099
1100Return `true` to optimize the image, `false` otherwise.
1101
1102**webpack.config.js**
1103
1104```js
1105const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1106
1107module.exports = {
1108 optimization: {
1109 minimizer: [
1110 "...",
1111 new ImageMinimizerPlugin({
1112 minimizer: {
1113 filter: (source, sourcePath) => {
1114 // The `source` argument is a `Buffer` of source file
1115 // The `sourcePath` argument is an absolute path to source
1116 if (source.byteLength < 8192) {
1117 return false;
1118 }
1119
1120 return true;
1121 },
1122 implementation: ImageMinimizerPlugin.imageminMinify,
1123 options: {
1124 plugins: [
1125 "imagemin-gifsicle",
1126 "imagemin-mozjpeg",
1127 "imagemin-pngquant",
1128 "imagemin-svgo",
1129 ],
1130 },
1131 },
1132 }),
1133 ],
1134 },
1135};
1136```
1137
1138##### `filename`
1139
1140Type:
1141
1142```ts
1143type filename =
1144 | string
1145 | ((
1146 pathData: {
1147 filename?: string | undefined;
1148 },
1149 assetInfo?: import("webpack").AssetInfo | undefined
1150 ) => string)
1151 | undefined;
1152```
1153
1154Default: `undefined`
1155
1156Allows to set the filename.
1157Supported values see in [`webpack template strings`](https://webpack.js.org/configuration/output/#template-strings), `File-level` section.
1158
1159We also support `[width]` and `[height]` placeholders (only `sharp` and `squoosh`).
1160
1161**webpack.config.js**
1162
1163```js
1164const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1165
1166module.exports = {
1167 optimization: {
1168 minimizer: [
1169 "...",
1170 new ImageMinimizerPlugin({
1171 minimizer: {
1172 filename: "optimized-[name][ext]",
1173 implementation: ImageMinimizerPlugin.squooshMinify,
1174 // Options
1175 options: {
1176 encodeOptions: {
1177 mozjpeg: {
1178 quality: 90,
1179 },
1180 },
1181 },
1182 },
1183 }),
1184 ],
1185 },
1186};
1187```
1188
1189Example `function` usage:
1190
1191**webpack.config.js**
1192
1193```js
1194const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1195
1196module.exports = {
1197 optimization: {
1198 minimizer: [
1199 "...",
1200 new ImageMinimizerPlugin({
1201 minimizer: {
1202 filename: () => "optimized-[name][ext]",
1203 implementation: ImageMinimizerPlugin.squooshMinify,
1204 // Options
1205 options: {
1206 encodeOptions: {
1207 mozjpeg: {
1208 quality: 90,
1209 },
1210 },
1211 },
1212 },
1213 }),
1214 ],
1215 },
1216};
1217```
1218
1219### `generator`
1220
1221Type:
1222
1223```ts
1224type generator = Array<{
1225 implementation: (
1226 original: {
1227 filename: string;
1228 data: Buffer;
1229 warnings: Array<Error>;
1230 errors: Array<Error>;
1231 info: import("webpack").AssetInfo;
1232 },
1233 options?:
1234 | {
1235 [key: string]: any;
1236 }
1237 | undefined
1238 ) => Promise<{
1239 filename: string;
1240 data: Buffer;
1241 warnings: Array<Error>;
1242 errors: Array<Error>;
1243 info: import("webpack").AssetInfo;
1244 }> & {
1245 setup?: (() => void) | undefined;
1246 teardown?: (() => void) | undefined;
1247 };
1248 options?:
1249 | {
1250 [key: string]: any;
1251 }
1252 | undefined;
1253 filter?: (source: Buffer, sourcePath: string) => boolean | undefined;
1254 filename?:
1255 | string
1256 | ((
1257 pathData: {
1258 filename?: string | undefined;
1259 },
1260 assetInfo?: import("webpack").AssetInfo | undefined
1261 ) => string)
1262 | undefined;
1263 preset?: string | undefined;
1264 type?: "import" | "asset" | undefined;
1265}>;
1266```
1267
1268Default: `undefined`
1269
1270Allow to setup default generators.
1271Useful if you need generate `webp`/`avif`/etc from other formats.
1272
1273> **Warning**
1274>
1275> 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.
1276
1277> **Warning**
1278>
1279> The option will not work if you disable `loader` (i.e. set the `loader` option to `false`).
1280
1281#### Available generators
1282
1283- `ImageMinimizerPlugin.imageminGenerate`
1284- `ImageMinimizerPlugin.squooshGenerate`
1285- `ImageMinimizerPlugin.sharpGenerate`
1286
1287#### Generator example for `imagemin`
1288
1289Example `webp` generator:
1290
1291**webpack.config.js**
1292
1293```js
1294const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1295
1296module.exports = {
1297 optimization: {
1298 minimizer: [
1299 "...",
1300 new ImageMinimizerPlugin({
1301 generator: [
1302 {
1303 // You can apply generator using `?as=webp`, you can use any name and provide more options
1304 preset: "webp",
1305 implementation: ImageMinimizerPlugin.imageminGenerate,
1306 options: {
1307 // Please specify only one plugin here, multiple plugins will not work
1308 plugins: ["imagemin-webp"],
1309 },
1310 },
1311 ],
1312 }),
1313 ],
1314 },
1315};
1316```
1317
1318#### Generator example for `squoosh`
1319
1320**webpack.config.js**
1321
1322```js
1323const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1324
1325module.exports = {
1326 optimization: {
1327 minimizer: [
1328 "...",
1329 new ImageMinimizerPlugin({
1330 generator: [
1331 {
1332 // You can apply generator using `?as=webp`, you can use any name and provide more options
1333 preset: "webp",
1334 implementation: ImageMinimizerPlugin.squooshGenerate,
1335 options: {
1336 encodeOptions: {
1337 // Please specify only one codec here, multiple codecs will not work
1338 webp: {
1339 quality: 90,
1340 },
1341 },
1342 },
1343 },
1344 ],
1345 }),
1346 ],
1347 },
1348};
1349```
1350
1351#### Generator example for `sharp`
1352
1353**webpack.config.js**
1354
1355```js
1356const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1357
1358module.exports = {
1359 optimization: {
1360 minimizer: [
1361 "...",
1362 new ImageMinimizerPlugin({
1363 generator: [
1364 {
1365 // You can apply generator using `?as=webp`, you can use any name and provide more options
1366 preset: "webp",
1367 implementation: ImageMinimizerPlugin.sharpGenerate,
1368 options: {
1369 encodeOptions: {
1370 // Please specify only one codec here, multiple codecs will not work
1371 webp: {
1372 quality: 90,
1373 },
1374 },
1375 },
1376 },
1377 ],
1378 }),
1379 ],
1380 },
1381};
1382```
1383
1384Now you can generate the new image using:
1385
1386```js
1387// Old approach for getting URL
1388import webp from "./file.jpg?as=webp";
1389
1390// Assets modules
1391console.log(new URL("./file.jpg?as=webp"));
1392```
1393
1394```css
1395div {
1396 background: url("./file.jpg?as=webp");
1397}
1398```
1399
1400You can use `?as=webp` in any type of files.
1401
1402Example multiple generators:
1403
1404**webpack.config.js**
1405
1406```js
1407const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1408
1409module.exports = {
1410 optimization: {
1411 minimizer: [
1412 "...",
1413 new ImageMinimizerPlugin({
1414 generator: [
1415 {
1416 // You can apply generator using `?as=webp`, you can use any name and provide more options
1417 preset: "webp",
1418 implementation: ImageMinimizerPlugin.squooshGenerate,
1419 options: {
1420 encodeOptions: {
1421 webp: {
1422 quality: 90,
1423 },
1424 },
1425 },
1426 },
1427 {
1428 // You can apply generator using `?as=avif`, you can use any name and provide more options
1429 preset: "avif",
1430 implementation: ImageMinimizerPlugin.squooshGenerate,
1431 options: {
1432 encodeOptions: {
1433 avif: {
1434 cqLevel: 33,
1435 },
1436 },
1437 },
1438 },
1439 ],
1440 }),
1441 ],
1442 },
1443};
1444```
1445
1446`squoosh` and `sharp` generator supports more options, for example you can resize an image:
1447
1448**webpack.config.js**
1449
1450```js
1451const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1452
1453module.exports = {
1454 optimization: {
1455 minimizer: [
1456 "...",
1457 new ImageMinimizerPlugin({
1458 generator: [
1459 {
1460 // You can apply generator using `?as=webp-100-50`, you can use any name and provide more options
1461 preset: "webp-100-50",
1462 // implementation: ImageMinimizerPlugin.sharpGenerate,
1463 implementation: ImageMinimizerPlugin.squooshGenerate,
1464 options: {
1465 resize: {
1466 enabled: true,
1467 width: 100,
1468 height: 50,
1469 },
1470 encodeOptions: {
1471 webp: {
1472 quality: 90,
1473 },
1474 },
1475 },
1476 },
1477 ],
1478 }),
1479 ],
1480 },
1481};
1482```
1483
1484You can find more information [here](https://github.com/GoogleChromeLabs/squoosh/tree/dev/libsquoosh).
1485
1486#### Generator example for user defined implementation
1487
1488You can use your own generator implementation.
1489
1490**webpack.config.js**
1491
1492```js
1493const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1494
1495module.exports = {
1496 optimization: {
1497 minimizer: [
1498 "...",
1499 new ImageMinimizerPlugin({
1500 generator: [
1501 {
1502 // You can apply generator using `?as=webp`, you can use any name and provide more options
1503 preset: "webp",
1504 implementation: async (original, options) => {
1505 const inputExt = path.extname(original.filename).toLowerCase();
1506
1507 if (inputExt !== ".xxx") {
1508 // Store error and return `null` if the implementation does not support this file type
1509 original.errors.push(error);
1510 return null;
1511 }
1512
1513 let result;
1514
1515 try {
1516 result = await minifyAndReturnBuffer(original.data);
1517 } catch (error) {
1518 // Store error and return `null` if there was an error
1519 original.errors.push(error);
1520 return null;
1521 }
1522
1523 return {
1524 filename: original.filename,
1525 data: result,
1526 warnings: [...original.warnings],
1527 errors: [...original.errors],
1528 info: {
1529 ...original.info,
1530 // Please always set it to prevent double minification
1531 generated: true,
1532 // Optional
1533 generatedBy: ["custom-name-of-minification"],
1534 },
1535 };
1536 },
1537 options: {
1538 // Your options
1539 },
1540 },
1541 ],
1542 }),
1543 ],
1544 },
1545};
1546```
1547
1548#### Generator options
1549
1550##### `type`
1551
1552Type:
1553
1554```ts
1555type type = "import" | "asset" | undefined;
1556```
1557
1558Default: `"import"`
1559
1560Allows you to apply the generator for `import` or assets from compilation (useful for copied assets).
1561By 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.
1562
1563**webpack.config.js**
1564
1565```js
1566const CopyPlugin = require("copy-webpack-plugin");
1567const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1568
1569module.exports = {
1570 optimization: {
1571 minimizer: [
1572 "...",
1573 new ImageMinimizerPlugin({
1574 minimizer: {
1575 implementation: ImageMinimizerPlugin.imageminMinify,
1576 options: {
1577 plugins: [
1578 "imagemin-gifsicle",
1579 "imagemin-mozjpeg",
1580 "imagemin-pngquant",
1581 "imagemin-svgo",
1582 ],
1583 },
1584 },
1585 generator: [
1586 {
1587 // Apply generator for copied assets
1588 type: "asset",
1589 // You can use `ImageMinimizerPlugin.squooshGenerate`
1590 // You can use `ImageMinimizerPlugin.sharpGenerate`
1591 implementation: ImageMinimizerPlugin.imageminGenerate,
1592 options: {
1593 plugins: ["imagemin-webp"],
1594 },
1595 },
1596 ],
1597 }),
1598 ],
1599 },
1600 plugins: [new CopyPlugin({ patterns: ["images/**/*.png"] })],
1601};
1602```
1603
1604##### `preset`
1605
1606Type:
1607
1608```ts
1609type preset = string | undefined;
1610```
1611
1612Default: `undefined`
1613
1614Configure the name of preset, i.e. you can use it in `?as=name`.
1615
1616**webpack.config.js**
1617
1618```js
1619const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1620
1621module.exports = {
1622 optimization: {
1623 minimizer: [
1624 "...",
1625 new ImageMinimizerPlugin({
1626 generator: [
1627 {
1628 preset: "name",
1629 // Implementation
1630 implementation: ImageMinimizerPlugin.squooshMinify,
1631 },
1632 ],
1633 }),
1634 ],
1635 },
1636};
1637```
1638
1639##### `implementation`
1640
1641Type:
1642
1643```ts
1644type implementation = (
1645 original: {
1646 filename: string;
1647 data: Buffer;
1648 warnings: Array<Error>;
1649 errors: Array<Error>;
1650 info: import("webpack").AssetInfo;
1651 },
1652 options?:
1653 | {
1654 [key: string]: any;
1655 }
1656 | undefined
1657) => Promise<{
1658 filename: string;
1659 data: Buffer;
1660 warnings: Array<Error>;
1661 errors: Array<Error>;
1662 info: import("webpack").AssetInfo;
1663}> & {
1664 setup?: (() => void) | undefined;
1665 teardown?: (() => void) | undefined;
1666};
1667```
1668
1669Default: `undefined`
1670
1671Configure the default `implementation`.
1672
1673**webpack.config.js**
1674
1675```js
1676const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1677
1678module.exports = {
1679 optimization: {
1680 minimizer: [
1681 "...",
1682 new ImageMinimizerPlugin({
1683 generator: [
1684 {
1685 preset: "name",
1686 // Implementation
1687 implementation: ImageMinimizerPlugin.squooshMinify,
1688 },
1689 ],
1690 }),
1691 ],
1692 },
1693};
1694```
1695
1696##### `options`
1697
1698Type:
1699
1700```ts
1701type options = {
1702 [key: string]: any;
1703};
1704```
1705
1706Default: `undefined`
1707
1708Options for the `implementation` option (i.e. options for `imagemin`/`squoosh`/`sharp`/custom implementation).
1709
1710**webpack.config.js**
1711
1712```js
1713const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1714
1715module.exports = {
1716 optimization: {
1717 minimizer: [
1718 "...",
1719 new ImageMinimizerPlugin({
1720 generator: [
1721 {
1722 preset: "name",
1723 implementation: ImageMinimizerPlugin.squooshMinify,
1724 // Options
1725 options: {
1726 encodeOptions: {
1727 mozjpeg: {
1728 quality: 90,
1729 },
1730 },
1731 },
1732 },
1733 ],
1734 }),
1735 ],
1736 },
1737};
1738```
1739
1740##### `filter`
1741
1742Type:
1743
1744```ts
1745type filter = (source: Buffer, sourcePath: string) => boolean;
1746```
1747
1748Default: `() => true`
1749
1750Allows filtering of images for optimization/generation.
1751
1752Return `true` to optimize the image, `false` otherwise.
1753
1754**webpack.config.js**
1755
1756```js
1757const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1758
1759module.exports = {
1760 optimization: {
1761 minimizer: [
1762 "...",
1763 new ImageMinimizerPlugin({
1764 generator: [
1765 {
1766 preset: "name",
1767 filter: (source, sourcePath) => {
1768 // The `source` argument is a `Buffer` of source file
1769 // The `sourcePath` argument is an absolute path to source
1770 if (source.byteLength < 8192) {
1771 return false;
1772 }
1773
1774 return true;
1775 },
1776 implementation: ImageMinimizerPlugin.imageminMinify,
1777 options: {
1778 plugins: [
1779 "imagemin-gifsicle",
1780 "imagemin-mozjpeg",
1781 "imagemin-pngquant",
1782 "imagemin-svgo",
1783 ],
1784 },
1785 },
1786 ],
1787 }),
1788 ],
1789 },
1790};
1791```
1792
1793##### `filename`
1794
1795Type:
1796
1797```ts
1798type filename =
1799 | string
1800 | ((
1801 pathData: PathData,
1802 assetInfo?: import("webpack").AssetInfo | undefined
1803 ) => string);
1804```
1805
1806Default: `undefined`
1807
1808Allows to set the filename.
1809Supported values see in [`webpack template strings`](https://webpack.js.org/configuration/output/#template-strings), `File-level` section.
1810
1811**webpack.config.js**
1812
1813```js
1814const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1815
1816module.exports = {
1817 optimization: {
1818 minimizer: [
1819 "...",
1820 new ImageMinimizerPlugin({
1821 generator: [
1822 {
1823 preset: "name",
1824 filename: "generated-[name][ext]",
1825 implementation: ImageMinimizerPlugin.squooshMinify,
1826 // Options
1827 options: {
1828 encodeOptions: {
1829 mozjpeg: {
1830 quality: 90,
1831 },
1832 },
1833 },
1834 },
1835 ],
1836 }),
1837 ],
1838 },
1839};
1840```
1841
1842Example of `function` usage:
1843
1844**webpack.config.js**
1845
1846```js
1847const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1848
1849module.exports = {
1850 optimization: {
1851 minimizer: [
1852 "...",
1853 new ImageMinimizerPlugin({
1854 generator: [
1855 {
1856 preset: "name",
1857 filename: () => "generated-[name][ext]",
1858 implementation: ImageMinimizerPlugin.squooshMinify,
1859 // Options
1860 options: {
1861 encodeOptions: {
1862 mozjpeg: {
1863 quality: 90,
1864 },
1865 },
1866 },
1867 },
1868 ],
1869 }),
1870 ],
1871 },
1872};
1873```
1874
1875#### `severityError`
1876
1877Type:
1878
1879```ts
1880type severityError = string;
1881```
1882
1883Default: `'error'`
1884
1885Allows to choose how errors are displayed.
1886
1887Сan have the following values:
1888
1889- `'off'` - suppresses errors and warnings
1890- `'warning'` - emit warnings instead errors
1891- `'error'` - emit errors
1892
1893**webpack.config.js**
1894
1895```js
1896const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1897
1898module.exports = {
1899 optimization: {
1900 minimizer: [
1901 "...",
1902 new ImageMinimizerPlugin({
1903 severityError: "warning",
1904 minimizer: {
1905 implementation: ImageMinimizerPlugin.imageminMinify,
1906 options: {
1907 plugins: [
1908 "imagemin-gifsicle",
1909 "imagemin-mozjpeg",
1910 "imagemin-pngquant",
1911 "imagemin-svgo",
1912 ],
1913 },
1914 },
1915 }),
1916 ],
1917 },
1918};
1919```
1920
1921#### `loader`
1922
1923Type:
1924
1925```ts
1926type loader = boolean;
1927```
1928
1929Default: `true`
1930
1931Automatically adding built-in `loader`, used to optimize/generate images.
1932
1933**webpack.config.js**
1934
1935```js
1936const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1937
1938module.exports = {
1939 optimization: {
1940 minimizer: [
1941 "...",
1942 new ImageMinimizerPlugin({
1943 loader: false,
1944 // `generator` will not work in this case
1945 minimizer: {
1946 implementation: ImageMinimizerPlugin.imageminMinify,
1947 options: {
1948 plugins: [
1949 "imagemin-gifsicle",
1950 "imagemin-mozjpeg",
1951 "imagemin-pngquant",
1952 "imagemin-svgo",
1953 ],
1954 },
1955 },
1956 }),
1957 ],
1958 },
1959};
1960```
1961
1962#### `concurrency`
1963
1964Type:
1965
1966```ts
1967type concurrency = number;
1968```
1969
1970Default: `Math.max(1, os.cpus().length - 1)`
1971
1972Maximum number of concurrency optimization processes in one time.
1973
1974**webpack.config.js**
1975
1976```js
1977const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
1978
1979module.exports = {
1980 optimization: {
1981 minimizer: [
1982 "...",
1983 new ImageMinimizerPlugin({
1984 concurrency: 3,
1985 minimizer: {
1986 implementation: ImageMinimizerPlugin.imageminMinify,
1987 options: {
1988 plugins: [
1989 "imagemin-gifsicle",
1990 "imagemin-mozjpeg",
1991 "imagemin-pngquant",
1992 "imagemin-svgo",
1993 ],
1994 },
1995 },
1996 }),
1997 ],
1998 },
1999};
2000```
2001
2002#### `deleteOriginalAssets`
2003
2004Type:
2005
2006```ts
2007type deleteOriginalAssets = boolean;
2008```
2009
2010Default: `true`
2011
2012Allows removing original assets after optimization.
2013
2014**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.**
2015
2016**webpack.config.js**
2017
2018```js
2019const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2020
2021module.exports = {
2022 optimization: {
2023 minimizer: [
2024 "...",
2025 new ImageMinimizerPlugin({
2026 // Disable loader
2027 loader: false,
2028 // Allows to keep original asset and minimized assets with different filenames
2029 deleteOriginalAssets: false,
2030 minimizer: {
2031 filename: "[path][name].webp",
2032 implementation: ImageMinimizerPlugin.imageminMinify,
2033 options: {
2034 plugins: [
2035 "imagemin-gifsicle",
2036 "imagemin-mozjpeg",
2037 "imagemin-pngquant",
2038 "imagemin-svgo",
2039 ],
2040 },
2041 },
2042 }),
2043 ],
2044 },
2045};
2046```
2047
2048## Loader Options
2049
2050- **[`minimizer`](#minimizer-1)**
2051- **[`generator`](#generator-1)**
2052- **[`severityError`](severityerror-1)**
2053
2054### `minimizer`
2055
2056Type:
2057
2058```ts
2059type minimizer =
2060 | {
2061 implementation: (
2062 original: {
2063 filename: string;
2064 data: Buffer;
2065 warnings: Array<Error>;
2066 errors: Array<Error>;
2067 info: import("webpack").AssetInfo;
2068 },
2069 options?:
2070 | {
2071 [key: string]: any;
2072 }
2073 | undefined
2074 ) => Promise<{
2075 filename: string;
2076 data: Buffer;
2077 warnings: Array<Error>;
2078 errors: Array<Error>;
2079 info: import("webpack").AssetInfo;
2080 }> & {
2081 setup?: (() => void) | undefined;
2082 teardown?: (() => void) | undefined;
2083 };
2084 options?:
2085 | {
2086 [key: string]: any;
2087 }
2088 | undefined;
2089 filter?: (source: Buffer, sourcePath: string) => boolean | undefined;
2090 filename?:
2091 | string
2092 | ((
2093 pathData: {
2094 filename?: string | undefined;
2095 },
2096 assetInfo?: import("webpack").AssetInfo | undefined
2097 ) => string)
2098 | undefined;
2099 }
2100 | Array<{
2101 implementation: (
2102 original: {
2103 filename: string;
2104 data: Buffer;
2105 warnings: Array<Error>;
2106 errors: Array<Error>;
2107 info: import("webpack").AssetInfo;
2108 },
2109 options?:
2110 | {
2111 [key: string]: any;
2112 }
2113 | undefined
2114 ) => Promise<{
2115 filename: string;
2116 data: Buffer;
2117 warnings: Array<Error>;
2118 errors: Array<Error>;
2119 info: import("webpack").AssetInfo;
2120 }> & {
2121 setup?: (() => void) | undefined;
2122 teardown?: (() => void) | undefined;
2123 };
2124 options?:
2125 | {
2126 [key: string]: any;
2127 }
2128 | undefined;
2129 filter?: (source: Buffer, sourcePath: string) => boolean | undefined;
2130 filename?:
2131 | string
2132 | ((
2133 pathData: {
2134 filename?: string | undefined;
2135 },
2136 assetInfo?: import("webpack").AssetInfo | undefined
2137 ) => string)
2138 | undefined;
2139 }>;
2140```
2141
2142Default: `undefined`
2143
2144Allows to setup default minimizer.
2145
2146#### Loader minimizer example for `imagemin`
2147
2148**webpack.config.js**
2149
2150```js
2151const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2152
2153module.exports = {
2154 module: {
2155 rules: [
2156 {
2157 test: /\.(jpe?g|png|gif|svg)$/i,
2158 type: "asset",
2159 },
2160 {
2161 test: /\.(jpe?g|png|gif|svg)$/i,
2162 loader: ImageMinimizerPlugin.loader,
2163 enforce: "pre",
2164 options: {
2165 minimizer: {
2166 implementation: ImageMinimizerPlugin.squooshMinify,
2167 options: {
2168 // Your options
2169 },
2170 },
2171 },
2172 },
2173 ],
2174 },
2175};
2176```
2177
2178For more information and supported options please read [here](#minimizer).
2179
2180### `generator`
2181
2182Type:
2183
2184```ts
2185type generator = Array<{
2186 implementation: TransformerFunction<T>;
2187 options?: BasicTransformerOptions<T>;
2188 filter?: FilterFn | undefined;
2189 filename?: string | FilenameFn | undefined;
2190 preset?: string | undefined;
2191 type?: "import" | "asset" | undefined;
2192}>;
2193```
2194
2195Default: `undefined`
2196
2197Allow to setup default generators.
2198Useful if you need generate `webp`/`avif`/etc from other formats.
2199
2200#### Loader generator example for `imagemin`
2201
2202**webpack.config.js**
2203
2204```js
2205const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2206
2207module.exports = {
2208 module: {
2209 rules: [
2210 {
2211 test: /\.(jpe?g|png|gif|svg)$/i,
2212 type: "asset",
2213 },
2214 {
2215 test: /\.(jpe?g|png|gif|svg)$/i,
2216 loader: ImageMinimizerPlugin.loader,
2217 enforce: "pre",
2218 options: {
2219 generator: [
2220 {
2221 preset: "webp",
2222 implementation: ImageMinimizerPlugin.imageminGenerate,
2223 options: {
2224 plugins: ["imagemin-webp"],
2225 },
2226 },
2227 ],
2228 },
2229 },
2230 ],
2231 },
2232};
2233```
2234
2235For more information and supported options please read [here](#generator).
2236
2237### `severityError`
2238
2239Type:
2240
2241```ts
2242type severityError = string;
2243```
2244
2245Default: `'error'`
2246
2247Allows to choose how errors are displayed.
2248
2249Сan have the following values:
2250
2251- `'off'` - suppresses errors and warnings
2252- `'warning'` - emit warnings instead errors
2253- `'error'` - emit errors
2254
2255**webpack.config.js**
2256
2257```js
2258const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2259
2260module.exports = {
2261 module: {
2262 rules: [
2263 {
2264 test: /\.(jpe?g|png|gif|svg)$/i,
2265 type: "asset",
2266 },
2267 {
2268 test: /\.(jpe?g|png|gif|svg)$/i,
2269 use: [
2270 {
2271 loader: ImageMinimizerPlugin.loader,
2272 options: {
2273 severityError: "warning",
2274 minimizerOptions: {
2275 plugins: ["gifsicle"],
2276 },
2277 },
2278 },
2279 ],
2280 },
2281 ],
2282 },
2283};
2284```
2285
2286## Additional API
2287
2288### `imageminNormalizeConfig(config)`
2289
2290The function normalizes configuration (converts plugins names and options to `Function`s) for using in `imagemin` package directly.
2291
2292```js
2293const imagemin = require("imagemin");
2294const { imageminNormalizeConfig } = require("image-minimizer-webpack-plugin");
2295
2296/*
2297 console.log(imageminConfig);
2298 =>
2299 {
2300 plugins: [Function, Function],
2301 pluginsMeta: [
2302 { name: "imagemin-jpegtran", version: "x.x.x", options: {} },
2303 { name: "imagemin-pngquant", version: "x.x.x", options: { quality: [0.6, 0.8] }
2304 ]
2305 }
2306*/
2307
2308(async () => {
2309 const imageminConfig = await imageminNormalizeConfig({
2310 plugins: ["jpegtran", ["pngquant", { quality: [0.6, 0.8] }]],
2311 });
2312 const files = await imagemin(["images/*.{jpg,png}"], {
2313 destination: "build/images",
2314 plugins: imageminConfig.plugins,
2315 });
2316
2317 console.log(files);
2318 // => [{data: <Buffer 89 50 4e …>, path: 'build/images/foo.jpg'}, …]
2319})();
2320```
2321
2322## Examples
2323
2324### Optimize images based on size
2325
2326You can use difference options (like `progressive`/`interlaced`/etc.) based on image size (example - don't do progressive transformation for small images).
2327
2328What is `progressive` image? [`Answer here`](https://jmperezperez.com/medium-image-progressive-loading-placeholder/).
2329
2330**webpack.config.js**
2331
2332```js
2333const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2334
2335module.exports = {
2336 optimization: {
2337 minimizer: [
2338 new ImageMinimizerPlugin({
2339 minimizer: {
2340 implementation: ImageMinimizerPlugin.imageminMinify,
2341 options: {
2342 plugins: [["jpegtran", { progressive: true }]],
2343 },
2344 // Only apply this one to files equal to or over 8192 bytes
2345 filter: (source) => {
2346 if (source.byteLength >= 8192) {
2347 return true;
2348 }
2349
2350 return false;
2351 },
2352 },
2353 }),
2354 new ImageMinimizerPlugin({
2355 minimizer: {
2356 implementation: ImageMinimizerPlugin.imageminMinify,
2357 options: {
2358 plugins: [["jpegtran", { progressive: false }]],
2359 },
2360 // Only apply this one to files under 8192
2361 filter: (source) => {
2362 if (source.byteLength < 8192) {
2363 return true;
2364 }
2365
2366 return false;
2367 },
2368 },
2369 }),
2370 ],
2371 },
2372};
2373```
2374
2375### Optimize and generate `webp` images
2376
2377- imagemin
2378
2379**webpack.config.js**
2380
2381```js
2382const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2383
2384module.exports = {
2385 optimization: {
2386 minimizer: [
2387 "...",
2388 new ImageMinimizerPlugin({
2389 minimizer: {
2390 implementation: ImageMinimizerPlugin.imageminMinify,
2391 options: {
2392 plugins: [
2393 "imagemin-gifsicle",
2394 "imagemin-mozjpeg",
2395 "imagemin-pngquant",
2396 "imagemin-svgo",
2397 ],
2398 },
2399 },
2400 generator: [
2401 {
2402 // You can apply generator using `?as=webp`, you can use any name and provide more options
2403 preset: "webp",
2404 implementation: ImageMinimizerPlugin.imageminGenerate,
2405 options: {
2406 plugins: ["imagemin-webp"],
2407 },
2408 },
2409 ],
2410 }),
2411 ],
2412 },
2413};
2414```
2415
2416- squoosh
2417
2418**webpack.config.js**
2419
2420```js
2421const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2422
2423module.exports = {
2424 optimization: {
2425 minimizer: [
2426 "...",
2427 new ImageMinimizerPlugin({
2428 minimizer: {
2429 implementation: ImageMinimizerPlugin.squooshMinify,
2430 },
2431 generator: [
2432 {
2433 // You can apply generator using `?as=webp`, you can use any name and provide more options
2434 preset: "webp",
2435 implementation: ImageMinimizerPlugin.squooshGenerate,
2436 options: {
2437 encodeOptions: {
2438 webp: {
2439 quality: 90,
2440 },
2441 },
2442 },
2443 },
2444 ],
2445 }),
2446 ],
2447 },
2448};
2449```
2450
2451- sharp
2452
2453**webpack.config.js**
2454
2455```js
2456const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2457
2458module.exports = {
2459 optimization: {
2460 minimizer: [
2461 "...",
2462 new ImageMinimizerPlugin({
2463 minimizer: {
2464 implementation: ImageMinimizerPlugin.sharpMinify,
2465 },
2466 generator: [
2467 {
2468 // You can apply generator using `?as=webp`, you can use any name and provide more options
2469 preset: "webp",
2470 implementation: ImageMinimizerPlugin.sharpGenerate,
2471 options: {
2472 encodeOptions: {
2473 webp: {
2474 quality: 90,
2475 },
2476 },
2477 },
2478 },
2479 ],
2480 }),
2481 ],
2482 },
2483};
2484```
2485
2486### Generate `webp` images from copied assets
2487
2488- imagemin
2489
2490**webpack.config.js**
2491
2492```js
2493const CopyPlugin = require("copy-webpack-plugin");
2494const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2495
2496module.exports = {
2497 optimization: {
2498 minimizer: [
2499 "...",
2500 new ImageMinimizerPlugin({
2501 minimizer: {
2502 implementation: ImageMinimizerPlugin.imageminMinify,
2503 options: {
2504 plugins: [
2505 "imagemin-gifsicle",
2506 "imagemin-mozjpeg",
2507 "imagemin-pngquant",
2508 "imagemin-svgo",
2509 ],
2510 },
2511 },
2512 generator: [
2513 {
2514 type: "asset",
2515 implementation: ImageMinimizerPlugin.imageminGenerate,
2516 options: {
2517 plugins: ["imagemin-webp"],
2518 },
2519 },
2520 ],
2521 }),
2522 ],
2523 },
2524 plugins: [new CopyPlugin({ patterns: ["images/**/*.png"] })],
2525};
2526```
2527
2528- squoosh
2529
2530**webpack.config.js**
2531
2532```js
2533const CopyPlugin = require("copy-webpack-plugin");
2534const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2535
2536module.exports = {
2537 optimization: {
2538 minimizer: [
2539 "...",
2540 new ImageMinimizerPlugin({
2541 minimizer: {
2542 implementation: ImageMinimizerPlugin.squooshMinify,
2543 },
2544 generator: [
2545 {
2546 type: "asset",
2547 implementation: ImageMinimizerPlugin.squooshGenerate,
2548 options: {
2549 encodeOptions: {
2550 webp: {
2551 quality: 90,
2552 },
2553 },
2554 },
2555 },
2556 ],
2557 }),
2558 ],
2559 },
2560 plugins: [new CopyPlugin({ patterns: ["images/**/*.png"] })],
2561};
2562```
2563
2564- sharp
2565
2566**webpack.config.js**
2567
2568```js
2569const CopyPlugin = require("copy-webpack-plugin");
2570const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
2571
2572module.exports = {
2573 optimization: {
2574 minimizer: [
2575 "...",
2576 new ImageMinimizerPlugin({
2577 minimizer: {
2578 implementation: ImageMinimizerPlugin.sharpMinify,
2579 },
2580 generator: [
2581 {
2582 type: "asset",
2583 implementation: ImageMinimizerPlugin.sharpGenerate,
2584 options: {
2585 encodeOptions: {
2586 webp: {
2587 quality: 90,
2588 },
2589 },
2590 },
2591 },
2592 ],
2593 }),
2594 ],
2595 },
2596 plugins: [new CopyPlugin({ patterns: ["images/**/*.png"] })],
2597};
2598```
2599
2600## Contributing
2601
2602Please take a moment to read our contributing guidelines if you haven't yet done so.
2603
2604[CONTRIBUTING](./.github/CONTRIBUTING.md)
2605
2606## License
2607
2608[MIT](./LICENSE)
2609
2610[npm]: https://img.shields.io/npm/v/image-minimizer-webpack-plugin.svg
2611[npm-url]: https://npmjs.com/package/image-minimizer-webpack-plugin
2612[node]: https://img.shields.io/node/v/image-minimizer-webpack-plugin.svg
2613[node-url]: https://nodejs.org
2614[tests]: https://github.com/webpack-contrib/image-minimizer-webpack-plugin/workflows/image-minimizer-webpack-plugin/badge.svg
2615[tests-url]: https://github.com/webpack-contrib/image-minimizer-webpack-plugin/actions
2616[cover]: https://codecov.io/gh/webpack-contrib/image-minimizer-webpack-plugin/branch/master/graph/badge.svg
2617[cover-url]: https://codecov.io/gh/webpack-contrib/image-minimizer-webpack-plugin
2618[chat]: https://badges.gitter.im/webpack/webpack.svg
2619[chat-url]: https://gitter.im/webpack/webpack
2620[size]: https://packagephobia.now.sh/badge?p=image-minimizer-webpack-plugin
2621[size-url]: https://packagephobia.now.sh/result?p=image-minimizer-webpack-plugin