Vite Plugin VSharp

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

A Vite plugin that compresses static images (jpg, png, gif, webp) after each build using sharp.js. Version 1.9.1 is the latest stable. Ideal for Vite projects needing automated image optimization without manual tooling. It works with Vite 2.6 to 5, handles public folder images, and offers per-format options. The plugin differs from others by being Vite-native, supporting exclude/include patterns for public assets, and allowing resizing and metadata preservation.

error Error: Cannot find module 'sharp'
cause Sharp is required but not installed. The plugin depends on sharp as a local package.
fix
Run 'npm install sharp' or ensure sharp is installed in your project.
error Error: [vsharp] excludePublic: pattern "public/*" must be a string or an array of strings
cause Incorrect type for excludePublic option.
fix
Provide an array of strings: excludePublic: ['public/*']
error TypeError: vsharp is not a function
cause Using CommonJS require with default import.
fix
Use ES module import: import vsharp from 'vite-plugin-vsharp'
breaking Plugin only works with Vite >=2.6 and <=5. Incompatible with Vite 6+.
fix Downgrade Vite to <=5 or switch to an alternative plugin that supports newer Vite.
deprecated The options 'publicDir' and 'outDir' are deprecated. Use 'excludePublic' and 'includePublic' instead.
fix Replace 'publicDir' with 'excludePublic' and 'outDir' with 'includePublic'.
gotcha Exclude patterns for public folders are relative to the project root, not the public folder itself.
fix Use patterns like 'public/images/*' without leading slash.
gotcha Setting 'scale' overrides 'width' and 'height'. Cannot use both.
fix Use either scale or width/height, not both.
npm install vite-plugin-vsharp
yarn add vite-plugin-vsharp
pnpm add vite-plugin-vsharp

Demonstrates setting up VSharp with custom options: per-format quality, exclusions, resizing, and metadata preservation.

// vite.config.js
import vsharp from 'vite-plugin-vsharp';

export default {
  plugins: [
    vsharp({
      // Compress all images with default settings
      // Override as needed:
      '.jpg': { quality: 80 },
      '.png': { quality: 80, palette: true },
      '.webp': { lossless: true },
      exclude: ['large-bg.png'],
      excludePublic: ['public/icons/*'],
      includePublic: ['public/images/keep/*'],
      width: 1920,
      height: 1080,
      preserveMetadata: { orientation: true },
    }),
  ],
};