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.
Common errors
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'.
Warnings
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.
Install
npm install vite-plugin-webp yarn add vite-plugin-webp pnpm add vite-plugin-webp Imports
- default wrong
import { webp } from 'vite-plugin-webp'correctimport webp from 'vite-plugin-webp' - vite.config.js (CommonJS) wrong
module.exports = { plugins: [webp] }correctconst webp = require('vite-plugin-webp') - Plugin usage in TypeScript wrong
const webp = require('vite-plugin-webp');correctimport webp from 'vite-plugin-webp'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [webp()] })
Quickstart
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 }
})
]
});