进阶 unplugin.unjs.io 2026-10-08 10:00:35 · 6 阅读

第8章 unplugin-imagemin:基于 Vite 的高性能图片压缩方案

26123 📦📦 unplugin Imagemin 图片压缩

​ 重要提示:unplugin-imagemin 正在准备发布 1.0 版本。该版本将在达成以下目标后发布: - [x] 通过重写 squoosh 的 wasm 语法,支持所有 Node.js 版本 - [x] 移除对 sharp 的依赖 - [x] 支持压缩 publicDir 中的图片 - [x] 支持压缩 CSS 中的图片 - [x] 支持全量缓存模式 - [x] 支持 Node 22 及更高版本 - [x] 类型化选项 - [ ] 支持 Farm、Rsbuild、Webpack 等其他框架

​ 警告:新功能与稳定性、兼容性及性能特性正在持续更新中,建议使用最新版本:

```bash pnpm add unplugin-imagemin@latest -D ```

​ 注意:由于 Google 已停止维护 Squoosh 的 Node.js 方向,本项目提供了一个 fork 版本并修复了一些兼容性问题,详情请见 squoosh-next。

✨✨ 测试中持续迭代开发

​

```bash # unplugin-imagemin ✔ 以 squoosh 模式启动处理 ✅ [test1.png] [12.39 MB] -> [102.54 KB] ✔ 以 squoosh 模式启动处理 ✅ [test2.png] [16.38 MB] -> [76.79 KB] ```

🌈 特性

🍰 支持 png、jpeg、webp、avif、svg、tiff 格式 🦾 基于 Squoosh 的高性能 ✨ 可配置多种图片格式 🪐 在构建时压缩代码 😃 缓存机制 🌈 可在构建时将不同图片类型相互转换

Squoosh && SVGO

unplugin-imagemin 支持两种压缩工具:

- Squoosh:一款通过多种格式减小图片体积的图像压缩 Web 应用,基于 Rust 和 WebAssembly 实现 - SVGO:支持压缩 SVG 格式图片

📦 安装

​

```bash pnpm add unplugin-imagemin@latest -D ```

支持 Vite 和 Rollup

​

基础用法(TypeScript):

```typescript import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import imagemin from 'unplugin-imagemin/vite';

// https://vitejs.dev/config/ export default defineConfig({ plugins: [vue(), imagemin()], }); ```

高级用法(TypeScript):

```typescript import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import imagemin from 'unplugin-imagemin/vite';

// https://vitejs.dev/config/ export default defineConfig({ plugins: [ vue(), imagemin({ // 默认值为 true cache: false, // 针对不同图片格式的默认压缩配置 compress: { jpg: { quality: 10, }, jpeg: { quality: 10, }, png: { quality: 10, }, webp: { quality: 10, }, }, conversion: [ { from: 'jpeg', to: 'webp' }, { from: 'png', to: 'webp' }, { from: 'JPG', to: 'jpeg' }, ], }), ], }); ```

🌸 默认配置

Squoosh 默认配置

详细默认配置请参考 [DefaultConfiguration](#)。插件属性配置请参考 [Configuration](#)。

TypeScript:

```typescript export interface PluginOptions { / * @description 图片编译和转换 * @default [] */ conversion?: ConversionItemType[]; / * @description 是否开启缓存 * @default true */ cache?: boolean; / * @description 缓存文件位置的路径 * @default ./node_modules/.cache/unplugin-imagemin/.unplugin-imagemin-cache */ cacheLocation?: string; / * @description 压缩选项 * @default CompressTypeOptions */ compress?: CompressTypeOptions; } ```

评论 (0)