vite-plugin-image-srcset

raw JSON →
0.1.1 verified Mon Apr 27 auth: no javascript

A Vite plugin (v0.1.1, latest) that automatically generates srcset attributes for responsive images by importing images with the ?srcset query. It expects images with @2x and @3x suffixes in the same directory, outputs an object with `src` and `srcSet` properties for 1x/2x/3x pixel densities. Supports PNG and JPG formats. Requires Vite 5+, 6+, or 7+. Ships TypeScript declarations. Minimal alternative to heavier image optimization plugins.

error Cannot find module 'vite-plugin-image-srcset/client'
cause Missing type reference configuration or incorrect import.
fix
Add "types": ["vite-plugin-image-srcset/client"] in tsconfig.json or add /// <reference types="vite-plugin-image-srcset/client" /> in a .d.ts file.
error Uncaught TypeError: Cannot read properties of undefined (reading 'src')
cause Importing an image without ?srcset query (returns a string instead of object).
fix
Use import img from './file.png?srcset' instead of import img from './file.png'
error The requested module 'vite-plugin-image-srcset' does not provide an export named 'default'
cause Using default import instead of named import.
fix
Change to: import { srcSetPlugin } from 'vite-plugin-image-srcset'
gotcha Images must follow naming convention: base (1x), base@2x.png, base@3x.png. Missing any will produce incomplete srcSet.
fix Ensure all three variants exist: icon.png, icon@2x.png, icon@3x.png.
gotcha Only .png and .jpg formats are supported. Using other extensions will not be transformed.
fix Convert images to .png or .jpg, or check plugin configuration for future format support.
gotcha The ?srcset query must be used; plain image imports without query will not be transformed.
fix Append ?srcset to the import path: import img from './image.png?srcset'
npm install vite-plugin-image-srcset
yarn add vite-plugin-image-srcset
pnpm add vite-plugin-image-srcset

Configures the plugin in Vite and demonstrates importing an image with ?srcset query to generate src and srcSet props for responsive images.

// vite.config.ts
import { defineConfig } from 'vite';
import { srcSetPlugin } from 'vite-plugin-image-srcset';

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

// App.tsx
import icon from './assets/icon.png?srcset';

function App() {
  return <img {...icon} alt="Icon" />;
}

// Ensure files exist:
// assets/icon.png, assets/icon@2x.png, assets/icon@3x.png