Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions packages/vite-plugin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# @srcset/vite-plugin

[![ESM-only package][package]][package-url]
[![NPM version][npm]][npm-url]
[![Node version][node]][node-url]
[![Dependencies status][deps]][deps-url]
[![Install size][size]][size-url]
[![Build status][build]][build-url]
[![Coverage status][coverage]][coverage-url]

[package]: https://img.shields.io/badge/package-ESM--only-ffe536.svg
[package-url]: https://nodejs.org/api/esm.html

[npm]: https://img.shields.io/npm/v/%40srcset%2Fvite-plugin.svg
[npm-url]: https://npmjs.com/package/@srcset/vite-plugin

[node]: https://img.shields.io/node/v/%40srcset%2Fvite-plugin.svg
[node-url]: https://nodejs.org

[deps]: https://img.shields.io/librariesio/release/npm/%40srcset%2Fvite-plugin
[deps-url]: https://libraries.io/npm/%40srcset%2Fvite-plugin

[size]: https://packagephobia.com/badge?p=%40srcset%2Fvite-plugin
[size-url]: https://packagephobia.com/result?p=%40srcset%2Fvite-plugin

[build]: https://img.shields.io/github/actions/workflow/status/TrigenSoftware/srcset/tests.yml?branch=main
[build-url]: https://github.com/TrigenSoftware/srcset/actions

[coverage]: https://img.shields.io/codecov/c/github/TrigenSoftware/srcset.svg
[coverage-url]: https://app.codecov.io/gh/TrigenSoftware/srcset

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
- 🌐 Pluggable backends: encode with [sharp](https://sharp.pixelplumbing.com/) or build [imgproxy](https://npmjs.com/package/@srcset/imgproxy) / [Cloudflare](https://npmjs.com/package/@srcset/cloudflare) urls

## Install

```bash
# 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

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

export default defineConfig({
plugins: [
srcset({
rules: [
{
match: '**/*.jpg',
width: [1, 0.5],
format: ['avif', 'webp', 'jpg']
},
{
match: '**/*.gif',
width: [1, 0.5],
format: ['webp', 'gif']
}
],
placeholder: true
})
]
})
```

```ts
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](https://srcset.js.org/integrations/vite-plugin/).
64 changes: 64 additions & 0 deletions packages/vite-plugin/client.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/* oxlint-disable trigen/import-order */
/// <reference types="vite/client" />
/**
* Ambient module declarations for image imports handled by @srcset/vite-plugin.
* Only the named exports are declared: the default url export
* comes from the `vite/client` asset types.
Comment thread
dangreen marked this conversation as resolved.
*
* Usage: add to tsconfig `types` or reference directly:
* /// <reference types="@srcset/vite-plugin/client" />
*/

Comment thread
dangreen marked this conversation as resolved.
Comment thread
dangreen marked this conversation as resolved.
declare module '*.jpg' {
Comment thread
dangreen marked this conversation as resolved.
Comment thread
dangreen marked this conversation as resolved.
import type { SrcSetEntry } from '@srcset/runtime'

export const src: SrcSetEntry
Comment thread
dangreen marked this conversation as resolved.
Comment thread
dangreen marked this conversation as resolved.
Comment thread
dangreen marked this conversation as resolved.
export const srcSet: SrcSetEntry[]
export const srcMap: Record<string, string>
export const placeholder: string | undefined
}

declare module '*.jpeg' {
import type { SrcSetEntry } from '@srcset/runtime'

export const src: SrcSetEntry
export const srcSet: SrcSetEntry[]
export const srcMap: Record<string, string>
export const placeholder: string | undefined
}

declare module '*.png' {
import type { SrcSetEntry } from '@srcset/runtime'

export const src: SrcSetEntry
Comment thread
dangreen marked this conversation as resolved.
export const srcSet: SrcSetEntry[]
export const srcMap: Record<string, string>
export const placeholder: string | undefined
}

declare module '*.webp' {
import type { SrcSetEntry } from '@srcset/runtime'

export const src: SrcSetEntry
export const srcSet: SrcSetEntry[]
export const srcMap: Record<string, string>
export const placeholder: string | undefined
}

declare module '*.avif' {
import type { SrcSetEntry } from '@srcset/runtime'

export const src: SrcSetEntry
export const srcSet: SrcSetEntry[]
export const srcMap: Record<string, string>
export const placeholder: string | undefined
}

declare module '*.gif' {
import type { SrcSetEntry } from '@srcset/runtime'

export const src: SrcSetEntry
export const srcSet: SrcSetEntry[]
export const srcMap: Record<string, string>
export const placeholder: string | undefined
}
12 changes: 12 additions & 0 deletions packages/vite-plugin/oxlint.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { defineConfig } from '@trigen/oxlint'
import testConfig from '@trigen/oxlint-config/test'
import tsTypeCheckedConfig from '@trigen/oxlint-config/typescript-type-checked'
import rootConfig from '../../oxlint.config.ts'

export default defineConfig({
extends: [
rootConfig,
tsTypeCheckedConfig,
testConfig
]
})
88 changes: 88 additions & 0 deletions packages/vite-plugin/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
{
"name": "@srcset/vite-plugin",
"type": "module",
"version": "1.0.0",
"description": "Vite plugin for generating responsive images.",
"author": {
"name": "Dan Onoshko",
"email": "danon0404@gmail.com",
"url": "https://github.com/dangreen"
},
"license": "MIT",
"homepage": "https://srcset.js.org/integrations/vite-plugin/",
"funding": "https://ko-fi.com/dangreen",
"repository": {
"type": "git",
"url": "https://github.com/TrigenSoftware/srcset.git",
"directory": "packages/vite-plugin"
},
"bugs": {
"url": "https://github.com/TrigenSoftware/srcset/issues"
},
"keywords": [
"srcset",
"image",
"picture",
"responsive",
"vite",
"vite-plugin"
],
"engines": {
"node": ">=22"
},
"sideEffects": false,
"exports": {
"./package.json": "./package.json",
".": "./src/index.ts",
"./client": {
"types": "./client.d.ts"
}
},
"publishConfig": {
"exports": {
"./package.json": "./package.json",
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./client": {
"types": "./client.d.ts"
}
},
"directory": "package",
"linkDirectory": false
},
"files": [
"dist",
"client.d.ts"
],
"scripts": {
"clear:package": "del ./package",
"clear:dist": "del ./dist",
"clear": "del ./package ./dist ./coverage",
"prepublishOnly": "run build clear:package clean-publish",
"postpublish": "pnpm clear:package",
"build": "tsc -p ./tsconfig.build.json",
"lint": "oxlint",
"format": "oxlint --fix",
"test:unit": "vitest run --coverage",
"test:unit:watch": "vitest watch",
"test:types": "tsc --noEmit",
"test": "run -p lint test:unit test:types"
},
"peerDependencies": {
"@srcset/runtime": "workspace:^",
"vite": ">=5"
},
"dependencies": {
"@srcset/bundler-utils": "workspace:^",
"@srcset/core": "workspace:^",
"p-limit": "^7.3.0"
},
"devDependencies": {
"@srcset/runtime": "workspace:^",
"@types/node": "^22.0.0",
"sharp": "^0.35.3",
"vite": "^8.1.0"
}
}
31 changes: 31 additions & 0 deletions packages/vite-plugin/src/dev.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {
describe,
it,
expect
} from 'vitest'
import {
type DevCache,
addDevImage
} from './dev.ts'

describe('vite-plugin', () => {
describe('dev', () => {
describe('addDevImage', () => {
it('should encode special characters in the pathname', () => {
const cache: DevCache = new Map()
const pathname = addDevImage(cache, {
path: '/images/my photo#1.jpg',
contents: Buffer.from('contents'),
format: 'jpg',
width: 640,
height: 480,
postfix: '',
originMultiplier: 1
})

expect(pathname).toMatch(/^\/@srcset\/my%20photo%231\.[0-9a-f]{8}\.jpg$/)
expect(cache.has(pathname)).toBe(true)
})
})
})
})
67 changes: 67 additions & 0 deletions packages/vite-plugin/src/dev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import type {
IncomingMessage,
ServerResponse
} from 'node:http'
import { createHash } from 'node:crypto'
import {
type SrcSetImage,
mimeTypes
} from '@srcset/core'

export const devPathPrefix = '/@srcset/'

const hashLength = 8

interface DevImage {
contents: Buffer
type: string
}

/**
* In-memory cache of the generated variants for the dev server middleware.
*/
export type DevCache = Map<string, DevImage>

/**
* Add an image variant to the dev cache.
* @param cache - Dev cache.
* @param image - Image variant.
* @returns Dev server pathname of the variant.
*/
export function addDevImage(cache: DevCache, image: SrcSetImage) {
const hash = createHash('sha256').update(image.contents).digest('hex').slice(0, hashLength)
const extensionIndex = image.path.lastIndexOf('.')
const stem = image.path.slice(image.path.lastIndexOf('/') + 1, extensionIndex)
// Encoded pathname is both the cache key and the public url: browsers
// percent-encode special characters in requests, the keys must match.
const pathname = `${devPathPrefix}${encodeURIComponent(`${stem}.${hash}.${image.format}`)}`

cache.set(pathname, {
contents: image.contents,
type: mimeTypes[image.format]
})

return pathname
}

/**
* Create a dev server middleware serving the generated variants from the cache.
* @param cache - Dev cache.
* @returns Connect-style middleware.
*/
export function createDevMiddleware(cache: DevCache) {
return (request: IncomingMessage, response: ServerResponse, next: () => void) => {
const url = request.url ?? ''
const index = url.indexOf(devPathPrefix)
const image = index < 0 ? undefined : cache.get(url.slice(index))

if (!image) {
next()
return
}

response.setHeader('Content-Type', image.type)
response.setHeader('Cache-Control', 'no-cache')
response.end(image.contents)
}
}
9 changes: 9 additions & 0 deletions packages/vite-plugin/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export { srcset } from './plugin.ts'
export type * from './types.ts'
export type {
SrcSetRule,
SrcSetEntrySelect,
SrcSetModuleEntry,
ResourceIdFormatter,
PlaceholderOptions
} from '@srcset/bundler-utils'
Loading