Home

Awesome

<h1 align="center"> <a target="_blank" rel="noopener noreferrer" href="https://github.com/vHeemstra/vite-plugin-imagemin/blob/main/packages/core/src/logo.svg?raw=true"><img src="https://github.com/vHeemstra/vite-plugin-imagemin/raw/main/packages/core/src/logo.svg?raw=true" alt="vite-plugin-imagemin - Vite + Imagemin" title="vite-plugin-imagemin - Vite + Imagemin" style="width: 75%; min-width: 280px; max-width: 800px; height: auto"></a><br>

GitHub release (latest SemVer) NPM version Build Status Coverall Coverage Status

</h1>

Minify bundled asset and static images in your Vite build with Imagemin. It optimizes all images you want, with the plugins you pick, using the configuration you choose.

Features

Install

npm install @vheemstra/vite-plugin-imagemin --save-dev

You also need to install the minifier plugins you want to use.

Usage

Add vite-plugin-imagemin and the minifier plugins to your vite.config.js:

// vite.config.js
import { defineConfig } from 'vite'
import viteImagemin from '@vheemstra/vite-plugin-imagemin'

// The minifiers you want to use:
import imageminMozjpeg from 'imagemin-mozjpeg'
import imageminWebp from 'imagemin-webp'

export default defineConfig({
  // ...your Vite config
  plugins: [
    // ...your other plugins
    viteImagemin({
      plugins: {
        jpg: imageminMozjpeg(),
      },
      makeWebp: {
        plugins: {
          jpg: imageminWebp(),
        },
      },
    }),
  ],
})

Options

plugins <sup>required</sup>

Type: object<br>

Object containing the minifiers to use per file extension, where:

All imagemin-* plugins can be used. See their documentation for install instructions and options. See also Suggested minifier plugins.

onlyAssets

Type: boolean<br> Default: false

Process only files in project's assets folder (true) or process all files in project's dist folder (false).

include

Type: String | RegExp | Array[...String|RegExp]<br> Default: /\.(png|jpg|jpeg|gif|svg)$/i

Valid picomatch pattern to include image files to minify (used in createFilter).

exclude

Type: String | RegExp | Array[...String|RegExp]<br> Default: /node_modules/

Valid picomatch pattern to exclude files from processing (used in createFilter).

formatFilePath

Type: function<br> Default: (file: string) => file

Callback function to change the output filepath, defaults to overwriting the original file.<br>The file argument holds the input filepath relative to the project's root directory (e.g. dist/assets/image.jpg).

skipIfLarger

Type: boolean<br> Default: true

Ignore the optimized output if it is larger than the original file.

makeAvif / makeWebp

Type: object<br> Default: undefined

Opt-in to create additional Avif and/or WebP versions of the processed images.

make*.plugins <sup>required</sup>

Type: object<br>

Same as options.plugins.

make*.formatFilePath

Type: function<br> Default: <code>(file: string) => `${file}.avif`</code>

Like options.formatFilePath, but by default the .avif/.webp extension is appended to the filepath.<br>The file argument holds the filepath as produced by options.formatFilePath.

make*.skipIfLargerThan

Type: false | 'original' | 'optimized' | 'smallest'<br> Default: 'optimized'

Skip Avif/WebP version if:

cache

Type: boolean<br> Default: true

Skip optimizing the input if it did not change since the last run.

cacheDir

Type: string<br> Default: <packageRoot>/node_modules/.cache/vite-plugin-imagemin/<packageName>/

Choose the directory to use for caching.

cacheKey

Type: string<br> Default: ''

Optional string to distinguish build configs and their caches.

The cache identifier is a hash of most used options including this key. Note: Because options like formatFilePath and plugins cannot be stringified, they will have little or no influence on the hash key and its uniqueness.

clearCache

Type: boolean<br> Default: false

Clears the cache folder before processing.

root

Type: string<br> Default: Vite's resolvedConfig.root or current working directory

Path to project root directory.

verbose

Type: boolean<br> Default: true

Whether to log process results to console.

logger

Type: object | Logger<br> Default: Vite's resolvedConfig.logger

Logger object with callback functions on the info, warn and error keys.

logByteDivider

Type: number<br> Default: 1000

Choose the size format to use in the logs:

Suggested minifier plugins

Optimize plugins

PluginRecommendedTypeOptions
imagemin-gifsicleGIFsee docs
imagemin-mozjpegJPGsee docs
imagemin-jpegoptimJPGsee docs
imagemin-jpegtranJPGsee docs
imagemin-pngquantPNGsee docs
imagemin-optipngPNGsee docs
imagemin-svgoSVGsee docs

Make plugins

PluginTypesOptions
imagemin-webpJPG / PNGsee docs
imagemin-gif2webpGIFsee docs
@vheemstra/imagemin-avifencJPG / PNGsee docs

Additional created versions can be delivered by the server if the client supports its format (see example config below). If not, the original (optimized) image can be delivered.

Tip: Use skipIfLargerThan option to ensure additional versions of images are smaller than the regular ones. (Otherwise, what was the point... :wink:)

Example .htaccess config for WebP

<IfModule mod_rewrite.c>
  RewriteEngine On

  # If browser supports WebP images...
  RewriteCond %{HTTP_ACCEPT} image/webp

  # ...and WebP replacement image exists in the same directory...
  RewriteCond %{REQUEST_FILENAME}.webp -f

  # ...serve WebP image instead of jpeg/png/gif.
  RewriteRule (.+)\.(jpe?g|png|gif)$ $1.webp [T=image/webp,E=REQUEST_image]

  # Same for AVIF
  RewriteCond %{HTTP_ACCEPT} image/avif
  RewriteCond %{REQUEST_FILENAME}.avif -f
  RewriteRule (.+)\.(jpe?g|png|gif)$ $1.avif [T=image/avif,E=REQUEST_image]
</IfModule>

<IfModule mod_headers.c>
  # Tell the browser the response (for this image) varies
  # depending on the "Accept" request header.
  Header append Vary Accept env=REQUEST_image
</IfModule>

<IfModule mod_mime.c>
  # Add file type MIME support
  AddType image/webp .webp
  AddType image/avif .avif
</IfModule>

Adopted from answers given here.

License

MIT

Related