Simple Vite plugin to generate srcset attributes for responsive images.
Import a single image and get src + srcSet for 1x/2x/3x pixel densities.
pnpm
pnpm add -D vite-plugin-image-srcsetnpm
npm install -D vite-plugin-image-srcsetyarn
yarn add -D vite-plugin-image-srcset// vite.config.ts
import { defineConfig } from 'vite';
import { srcSetPlugin } from 'vite-plugin-image-srcset';
export default defineConfig({
plugins: [srcSetPlugin()],
});Add to your tsconfig.json:
{
"compilerOptions": {
"types": ["vite-plugin-image-srcset/client"]
}
}Or add a reference in your vite-env.d.ts:
/// <reference types="vite/client" />
+ /// <reference types="vite-plugin-image-srcset/client" />The plugin expects images with @2x and @3x suffixes:
assets/
icon.png # 1x (base)
icon@2x.png # 2x
icon@3x.png # 3x
Missing densities are skipped rather than failing the build — if only icon.png and
icon@2x.png exist, the generated srcSet contains just those two candidates.
import icon from './assets/icon.png?srcset';
// icon = { src: '/assets/icon.png', srcSet: '/assets/icon.png 1x, /assets/icon@2x.png 2x, /assets/icon@3x.png 3x' }import icon from './assets/icon.png?srcset';
function App() {
return <img {...icon} alt="Icon" />;
}import icon from './assets/icon.png?srcset';
document.body.innerHTML = `<img src="${icon.src}" srcset="${icon.srcSet}" alt="Icon" />`;The plugin transforms imports with ?srcset query into an object:
interface ImageSrcSet {
src: string; // URL of the lowest available density
srcSet: string; // srcset string: "url1 1x, url2 2x, url3 3x"
}srcSetPlugin({
densities: [1, 2, 3], // Pixel densities to generate.
suffix: (baseName, density) => `${baseName}@${density}x`, // Builds the file name for densities > 1.
extensions: ['.png', '.jpg', '.jpeg', '.webp', '.avif'], // Extensions handled by the plugin.
});.png.jpg/.jpeg.webp.avif
Other extensions are left untouched. The list is configurable via the extensions
option, but the bundled type declarations only cover the formats above — for anything
else, declare the module yourself:
declare module '*.gif?srcset' {
const srcset: import('vite-plugin-image-srcset').ImageSrcSet;
export default srcset;
}MIT