Skip to content

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.

A noisy purple-to-blue gradient used to demonstrate PNG optimization

Open your browser's network tab and compare the transferred size to the source size above.

Install ​

sh
npm install --save-dev @binarynoir/vite-plugin-optimize-images

Use ​

ts
// 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 ​

OptionDefaultDescription
minSize10240Minimum source size in bytes before an image is considered (10 KiB).
minSavings1024Minimum bytes an optimization must save before it is applied (1 KiB).
png / jpeg / webpnonesharp encode options overrides.
verbosefalseLog progress and per-file savings.

Defaults before any override:

ts
{
  png: { quality: 80, compressionLevel: 9, adaptiveFiltering: true },
  jpeg: { quality: 85, progressive: true, mozjpeg: true },
  webp: { quality: 85 },
}

Source and full README on GitHub

Code released under the MIT License. BinaryNoir name and logos are trademarks of BinaryNoir. Legal · Terms · Privacy