Simple Vite plugin to generate srcset attributes for images
npm install vite-plugin-image-srcsetSimple Vite plugin to generate srcset attributes for responsive images.
Import a single image and get src + srcSet for 1x/2x/3x pixel densities.
``bash`
npm install -D vite-plugin-image-srcsetor
pnpm add -D vite-plugin-image-srcset
`ts
// vite.config.ts
import { defineConfig } from 'vite';
import { srcSetPlugin } from 'vite-plugin-image-srcset';
export default defineConfig({
plugins: [srcSetPlugin()],
});
`
Add to your tsconfig.json:
`json`
{
"compilerOptions": {
"types": ["vite-plugin-image-srcset/client"]
}
}
Or add a reference in your vite-env.d.ts:
`ts`
///
+ ///
The plugin expects images with @2x and @3x suffixes:
``
assets/
icon.png # 1x (base)
icon@2x.png # 2x
icon@3x.png # 3x
`tsx
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' }
`
`tsx
import icon from './assets/icon.png?srcset';
function App() {
return ;
}
`
`ts
import icon from './assets/icon.png?srcset';
document.body.innerHTML = ;`
The plugin transforms imports with ?srcset query into an object:
`ts`
interface ImageSrcSet {
src: string; // URL to 1x image
srcSet: string; // srcset string: "url1 1x, url2 2x, url3 3x"
}
- .png.jpg`
-
MIT