vite-plugin-webp

raw JSON →
1.1.3 verified Mon Apr 27 auth: no javascript

A Vite plugin that converts JPEG, PNG, GIF, and AVIF images to WebP format during the build process, using the sharp library for high-performance conversion. Version 1.1.3 is the latest stable release. It supports CSS background images (with a fallback class-based approach) and JS image imports with clip (dimension-based) transformations. Key differentiator: automatic inline conversion in CSS and JS without manual WebP management, plus image clipping via filename dimensions.

error Error: Cannot find module 'sharp'
cause sharp is not installed because it's an optional dependency.
fix
Run 'npm install sharp' to add sharp as a direct dependency.
error Uncaught TypeError: webp is not a function
cause Using named import instead of default import.
fix
Change import to 'import webp from 'vite-plugin-webp'' (without curly braces).
error [vite] Internal server error: The plugin 'vite-plugin-webp' caused a build error: Invalid key 'shartOptions'
cause Typo in option name 'shartOptions' instead of 'sharpOptions'.
fix
Use correct option name 'sharpOptions'.
gotcha Option name misspelled: 'declude' instead of 'exclude'. The README uses 'declude' (typo) but the actual plugin option is 'exclude'.
fix Use 'exclude' option; if you copy from the README, correct the spelling.
gotcha Option 'shartOptions' is a typo in the README; the correct option is 'sharpOptions'.
fix Use 'sharpOptions' in your config.
gotcha Clip feature requires careful filename format: 'example240x250.png' to produce 240x250 WebP. This is not documented clearly and may cause unexpected behavior.
fix Name your images with dimensions in the filename, e.g., 'image240x250.png'.
gotcha The plugin only transforms images inside 'include' paths (if specified) and respects 'exclude' paths. Omitting 'include' will process all images in the project, which may slow down builds.
fix Set 'include' to a specific directory to limit conversion scope.
npm install vite-plugin-webp
yarn add vite-plugin-webp
pnpm add vite-plugin-webp

Basic configuration of vite-plugin-webp in vite.config.js, showing include, exclude, imageType, and sharpOptions.

import webp from 'vite-plugin-webp';
import path from 'path';

export default defineConfig({
  plugins: [
    webp({
      include: path.join(__dirname, 'src/pages/index'),
      exclude: path.join(__dirname, 'src/pages/index/ignore.vue'),
      imageType: ['.png', '.jpg'],
      sharpOptions: { quality: 100 }
    })
  ]
});