Optimize Images Vite plugin
Reading Time
Reading time for this document is 1 minute for 191 words.
@binarynoir/vite-plugin-optimize-images re-compresses the PNG, JPEG and WebP images in your build output using sharp. Your source files are never touched, only images that actually ship get processed, and you never end up with a bigger file: if re-compressing wouldn't save meaningful space, the original is kept.
See it live
The image below is a deliberately heavy, noisy PNG generated by scripts/generate-demo-image.mjs. The file committed to this repository is about 2.4 MB. This site's build runs with verbose: true, so the build log prints the savings for it. The copy you are downloading right now is the optimized one.

Open your browser's network tab and compare the transferred size to the source size above.
Install
npm install --save-dev @binarynoir/vite-plugin-optimize-imagesUse
// vite.config.ts, or inside `vite: { plugins: [...] }` in a VitePress config
import { optimizeImagesPlugin } from '@binarynoir/vite-plugin-optimize-images';
export default defineConfig({
plugins: [optimizeImagesPlugin()],
});Options
| Option | Default | Description |
|---|---|---|
minSize | 10240 | Minimum source size in bytes before an image is considered (10 KiB). |
minSavings | 1024 | Minimum bytes an optimization must save before it is applied (1 KiB). |
png / jpeg / webp | none | sharp encode options overrides. |
verbose | false | Log progress and per-file savings. |
Defaults before any override:
{
png: { quality: 80, compressionLevel: 9, adaptiveFiltering: true },
jpeg: { quality: 85, progressive: true, mozjpeg: true },
webp: { quality: 85 },
}