November 10, 2024

Optimize Static Images Automatically

If you’ve ever wanted to optimize static images automatically, you’ve come to the right place. In SvelteKit, you can use the @sveltejs/enhanced-img package to optimize images automatically. It’s very straightforward to use, and it automatically generates AVIF and WebP images for the width and height you specify.

Install enhanced:img

To install enhanced:img, run following command:

bun i -D @sveltejs/enhanced-img

Then add it to vite.config.ts file:

import { enhancedImages } from "@sveltejs/enhanced-img";

export default defineConfig({
  plugins: [enhancedImages()],
});

Use enhanced:img in your components

When you want to optimize image automatically, change img to enhanced:img and add /static to the src attribute. For instance, if you have this image in your component:

<img class="w-24" src="/logo.png" width="192" height="192" alt="SvelteRust" />

You can change it to this to automatically optimize the image. enhanced:img automatically adds width and height attributes, as well as generating picture tag with the different image formats.

<enhanced:img class="w-24" src="/static/logo.png?w=192" alt="SvelteRust" />

For HIDPI screens, you should set the width to 2x the displayed size like I’ve done above. This way, you get crisp image quality.