Image Optimization with vite-imagetools

September 16th 2023

For many websites, the images on the site are the largest files that need to be sent to the user. In order to improve page loads and user experience it is necessary to serve up compressed images instead of their often very large originals.

There are a lot of ways to achieve this and the best way depends on a lot factors specific to the particular site. I recently was working on a static site developed with SvelteKit. SvelteKit uses Vite and I found a well maintained image optimization library that seemed to fit my workflow well for this particular project. The tool is called vite-imagetools. Once setup, image sizes (as well as other options like format) can be specified by adding information to the end of the import statement. When the site is built, vite-imagetools creates a compressed image and handles creating the proper import for this compressed image.

import compressedSrc from '$lib/images/example.jpg?w=400';

It was very easy to setup and use as it had very good documentation. There was only one issue I had and this was with typescript. The typescript linter in VS Code complained about these import statements. Luckily, plenty of others had this same issue so I quickly found a relevant dicussion of the issue. There, users presented several viable solutions. The one I liked the most was adding the following to app.d.ts.

declare module '*&imagetools' {
	/**
	 * actual types
	 * - code https://github.com/JonasKruckenberg/imagetools/blob/main/packages/core/src/output-formats.ts
	 * - docs https://github.com/JonasKruckenberg/imagetools/blob/main/docs/guide/getting-started.md#metadata
	 */
	const out;
	export default out;
}

Then I could simple append &imagetools to the end of the import statements.

import compressedSrc from '$lib/images/example.jpg?w=400&imagetools';