Skip to content

Latest commit

 

History

History

README.md

@srcset/vite-plugin

ESM-only package NPM version Node version Dependencies status Install size Build status Coverage status

Vite plugin for generating responsive images.

  • 🧩 Image imports are processed by default; native Vite queries like ?url stay in the asset pipeline
  • 🌳 Tree-shakable image modules: unused exports are dropped from the bundle
  • 🌫 Blur-up placeholders inlined as data-urls
  • 🖼 Variants encoded with sharp: widths, modern formats and optimization

Install

# pnpm
pnpm add -D @srcset/vite-plugin @srcset/runtime
# yarn
yarn add -D @srcset/vite-plugin @srcset/runtime
# npm
npm i -D @srcset/vite-plugin @srcset/runtime

Usage

// vite.config.js
import { defineConfig } from 'vite'
import { srcset } from '@srcset/vite-plugin'

export default defineConfig({
  plugins: [
    srcset({
      rules: [
        // First format is the fallback: default export and src
        {
          match: '**/*.jpg',
          width: [1, 0.5],
          format: ['jpg', 'webp', 'avif']
        },
        {
          match: '**/*.gif',
          width: [1, 0.5],
          format: ['gif', 'webp']
        }
      ],
      placeholder: true
    })
  ]
})
import url, { src, srcSet, srcMap, placeholder } from './photo.jpg'

// url - url of the selected variant, e.g. '/assets/photo.f37e2d3a.jpg'
// src - selected variant: { id: 'jpg1200', format: 'jpg', type: 'image/jpeg', width: 1200, height: 800, url }
// srcSet - array of all generated variants
// srcMap - id-to-url map, e.g. srcMap.webp600
// placeholder - blur-up data-url, when the `placeholder` option is enabled

const img = `<img src="${url}" srcset="${srcSet.map(({ url, width }) => `${url} ${width}w`).join(', ')}">`

The module is tree-shakable: import only what you use - the rest is dropped from the bundle.

Documentation

For more details, guides and API references, check out the documentation website.