Optimizing WebP, AVIF, and fallback images in Vite
Optimize image assets with Vite, Sharp, and SVGO, then serve explicit AVIF and WebP variants with a picture element and a fallback image.
A high-resolution hero image can dominate a page’s cold-load transfer. I use format-specific optimization during the build and publish explicit variants so the browser can choose an image it decodes.
Choosing a fallback and modern formats
| Format | Where I use it |
|---|---|
| PNG | Graphics or transparency that need a compatible fallback |
| JPEG | A compatible photographic fallback |
| WebP | A smaller image with broad browser support |
| AVIF | A candidate when its quality and transfer size are better at the target dimensions |
File sizes depend on the source image, dimensions, encoder, and quality settings. The biggest savings can come from reducing the image to the dimensions the page needs. Then compare codecs at a comparable visual quality. Test logos and photos separately.
Separate variant generation from optimization
vite-plugin-image-optimizer applies Sharp or SVGO options to assets in the build. The configuration below tells it how to optimize each matching format. To publish new AVIF and WebP files from a PNG source, generate those variants first. For example, a prebuild script can call sharp(input).avif(options).toFile(avifPath) and sharp(input).webp(options).toFile(webpPath). Place the generated files in the intended asset directory before the Vite build copies or processes them.
flowchart TD
SRC["Source images"] --> GEN["Create WebP and AVIF variants"]
GEN --> OPT["Optimize assets by format"]
SRC --> OPT
OPT --> DIST["Publish variants and fallback"]
DIST --> B["Browser selects a picture source"]
Adding the optimizer to the Vite build
Install the plugin with Sharp and SVGO. includePublic: true covers the example’s public images. The settings below allow lossy encoding for modern formats, so review the output before applying the same policy to every asset. The SVGO rule retains viewBox so the SVG can scale.
1
2
# Install the optimizer and its engines
pnpm add -D vite-plugin-image-optimizer sharp svgo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { ViteImageOptimizer } from 'vite-plugin-image-optimizer';
export default defineConfig({
plugins: [
react(),
ViteImageOptimizer({
// Match the supported image extensions.
test: /\.(jpe?g|png|gif|tiff|webp|svg|avif)$/i,
includePublic: true, // Include assets from the public directory.
logStats: true, // Show optimization statistics in the build output.
// Set optimization options for each format.
png: {
quality: 85,
compressionLevel: 8,
},
jpeg: {
quality: 80,
progressive: true,
},
webp: {
lossless: false,
quality: 80,
},
avif: {
lossless: false,
quality: 75,
effort: 5, // AVIF encoder effort (0-9).
},
svg: {
multipass: true,
plugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false, // Keep viewBox for responsive sizing.
},
},
},
'sortAttrs',
{
name: 'addAttributesToSVGElement',
params: {
attributes: [{ xmlns: 'http://www.w3.org/2000/svg' }],
},
},
],
},
}),
],
});
Letting the browser choose a variant
A picture element lists AVIF first and WebP second, then falls back to the img source. Each source includes its media type. Keep meaningful alternate text on the img element. The sample uses lazy loading for a reusable image component. If the image is the above-the-fold LCP candidate, use eager loading for that instance and verify the waterfall.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// src/components/OptimizedImage.tsx
import React from 'react';
interface OptimizedImageProps {
name: string; // Example: 'hero-banner'
alt: string;
className?: string;
}
export const OptimizedImage: React.FC<OptimizedImageProps> = ({
name,
alt,
className,
}) => {
return (
<picture className={className}>
{/* 1. Prefer AVIF where supported. */}
<source
type="image/avif"
srcSet={`/assets/images/${name}.avif`}
/>
{/* 2. Offer WebP as the next source. */}
<source
type="image/webp"
srcSet={`/assets/images/${name}.webp`}
/>
{/* 3. Keep a PNG fallback. */}
<img
src={`/assets/images/${name}.png`}
alt={alt}
loading="lazy"
decoding="async"
/>
</picture>
);
};
Keep the relative URL strategy consistent with deployment. In the sample, the absolute /assets/images/ path assumes the site serves those files at its root. Use the application’s base path for a subdirectory deployment.
Checking source and output sizes
Run pnpm build and inspect the optimizer report. The example log shows the hero PNG moving from 2,450.12 kB to 384.20 kB and the feature JPEG from 1,280.40 kB to 192.10 kB. The SVG and partner image also shrink. Those values describe the assets in the recorded build.
Figure 1. The build report lists the size of each optimized asset.
Inspect the files in dist/assets/images as well. The recorded hero variants were 248 kB for AVIF and 384 kB for WebP. Confirm that the files exist, are served with the intended content types, and match the URLs in the component.
Figure 2. The output directory contains both modern hero variants.
Finally, load the page and check currentSrc and the network waterfall under actual supported browsers. Measure the first-load transfer and the LCP candidate under the same conditions as the baseline. Keep compression and code splitting measurements separate so you can tell where the improvement came from.