VSharp is a Vite plugin that makes image optimization easy. It uses the powerful Sharp library to automatically compress your images during the build process. This means faster-loading websites with high-quality images, all without any extra work on your part.
.jpg/.jpeg
, .png
, .gif
, and .webp
Add VSharp to your project:
npm install vite-plugin-vsharp --save-dev
Add VSharp to your Vite config file:
// vite.config.js
import vsharp from 'vite-plugin-vsharp';
export default {
plugins: [
vsharp({
// Your options here
}),
],
};
Here’s how you can customize VSharp to fit your needs:
exclude
: Skip specific images during compression. Just list the filenames:
// vite.config.js
{
plugins: [
vsharp({
exclude: [
"bg.jpg", // Won't compress this file
// Note: Just use filenames, no paths needed
],
}),
]
}
excludePublic
: Skip images in your public folder using patterns:
// vite.config.js
{
plugins: [
vsharp({
excludePublic: [
"public/*", // Skip everything in public
"public/test_img/*", // Skip all images in test_img
],
}),
]
}
includePublic
: Choose specific files to compress from excluded folders:
// vite.config.js
{
plugins: [
vsharp({
excludePublic: [
"public/*" // Skip all public files
],
includePublic: [
"public/images/*", // But compress files in this folder
"public/test_img/001.jpg", // And this specific image
],
}),
]
}
Note: includePublic
takes priority over excludePublic
, letting you:
Image Size Options: Control how your images are resized:
// vite.config.js
{
plugins: [
vsharp({
width: 800, // Maximum width (won't upscale smaller images)
height: 800, // Maximum height (won't upscale smaller images)
scale: 0.8, // Or use this to reduce by percentage (overrides width/height)
}),
]
}
Metadata Options: Keep important image information:
// vite.config.js
{
plugins: [
vsharp({
preserveMetadata: {
orientation: true, // Keeps correct image orientation
},
}),
]
}
VSharp comes with these sensible defaults, which you can override as needed:
{
"includePublic": [],
"excludePublic": [],
"exclude": [],
".jpg": {
"quality": 80
},
".jpeg": {
"quality": 80
},
".png": {
"quality": 80,
"palette": true
},
".webp": {
"lossless": true
},
".gif": {
},
"preserveMetadata": {
"orientation": false
}
}
For more advanced options, check out the Sharp documentation.