Vite 中文文档 Vite 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • vite

    • 指引
    • 为什么选 Vite
    • 开始
    • 功能
    • 命令行界面
    • 使用插件
    • 依赖预构建
    • 静态资源处理
    • 构建生产版本
    • 部署静态站点
    • 环境变量和模式
    • 服务端渲染
    • 后端集成
    • 与其他工具比较
    • 故障排除
    • 从 v3 迁移
  • API

  • 配置参考

  • vite

  • API

  • 配置参考


  vite-plugin-image-presets

Image Presets for Vite.js apps

This Vite plugin allows you to define presets for image processing using Sharp, allowing you to optimize, resize, and process images consistently and with ease.

Demo 🖼

Installation 💿


  1. ``` shell
  2. npm install -D vite-plugin-image-presets # pnpm, yarn
  3. ```

Configuration ⚙️


Add it to your plugins in vite.config.ts

  1. ``` ts
  2. import { defineConfig } from 'vite'
  3. import imagePresets, { widthPreset } from 'vite-plugin-image-presets'

  4. export default defineConfig({
  5.   plugins: [
  6.     imagePresets({
  7.       thumbnail: widthPreset({
  8.         class: 'img thumb',
  9.         loading: 'lazy',
  10.         widths: [48, 96],
  11.         formats: {
  12.           webp: { quality: 50 },
  13.           jpg: { quality: 70 },
  14.         },
  15.       }),
  16.     }),
  17.   ],
  18. })
  19. ```

Usage 🚀


Use the preset query parameter to obtain an array of source and img attrs:

  1. ``` js
  2. import thumbnails from '~/images/logo.jpg?preset=thumbnail'

  3. expect(thumbnails).toEqual([
  4.   {
  5.     type: 'image/webp',
  6.     srcset: '/assets/logo.ffc730c4.webp 48w, /assets/logo.1f874174.webp 96w',
  7.   },
  8.   {
  9.     type: 'image/jpeg',
  10.     srcset: '/assets/logo.063759b1.jpeg 48w, /assets/logo.81d93491.jpeg 96w',
  11.     src: '/assets/logo.81d93491.jpeg',
  12.     class: 'img thumb',
  13.     loading: 'lazy',
  14.   },
  15. ])
  16. ```

You can also use the src and srcset query parameters for direct usage:

  1. ``` js
  2. import srcset from '~/images/logo.jpg?preset=thumbnail&srcset'
  3. import src from '~/images/logo.jpg?preset=thumbnail&src'

  4. expect(srcset).toEqual('/assets/logo.063759b1.jpeg 48w, /assets/logo.81d93491.jpeg 96w')
  5. expect(src).toEqual('/assets/logo.81d93491.jpeg')
  6. ```

Check the example for additional usage information and different preset examples, or see it live.

Documentation 📖


Additional usage documentation coming soon.

In the meantime, check the @islands/images module for îles.

Acknowledgements


sharp : High performance Node.js image processing
vite-imagetools : The middleware used in development is based on this nice library.

The hdPreset is based on the following article by Jake Archibald:

Halve the size of images by optimising for high density displays

License


This library is available as open source under the terms of the MIT License.
Last Updated: 2023-05-23 11:11:51