一、前言
在前端工程化中,图片优化是提升项目性能的重要环节之一,也是提升性能的关键步骤。vite-plugin-imagemin
提供了丰富的配置选项,支持 GIF、PNG、JPG、SVG 等格式的压缩。本文将详细介绍该插件的完整配置及各参数的作用。告诉大家如何在 Vite 中使用 vite-plugin-imagemin
对图片进行高效压缩,减少加载时间,提高用户体验。
二、安装 vite-plugin-imagemin
在 Vite 项目中,使用 vite-plugin-imagemin
进行图片压缩。首先安装插件:
bash
复制代码
# 写这篇文章的时候,版本是 0.6.1
pnpm add vite-plugin-imagemin -D
三、配置 vite.config.ts
在 vite.config.ts
中配置 vite-plugin-imagemin
,同时判断当前环境是否是生产模式:
ts
复制代码
import { defineConfig } from 'vite'
import viteImagemin from 'vite-plugin-imagemin'
export default defineConfig(({ command }) => {
const isBuild = command === 'build' // 是否为生产模式
return {
plugins: [
viteImagemin({
gifsicle: {
interlaced: true, // 隔行扫描
optimizationLevel: 3, // 压缩级别(0-3)
},
optipng: {
optimizationLevel: 5, // 压缩级别(0-7),值越大压缩率越高
},
mozjpeg: {
quality: 80, // 压缩质量(0-100)
progressive: true, // 渐进式加载
smooth: 2, // 平滑处理,减少色彩失真
},
svgo: {
plugins: [
{ name: 'removeViewBox', active: false }, // 保留 viewBox 以防止 SVG 变形
{ name: 'removeEmptyAttrs', active: true }, // 移除空属性
{ name: 'convertColors', params: { currentColor: true } }, // 颜色转换
]
},
webp: {
quality: 80, // WebP 质量(0-100)
lossless: false, // 是否无损压缩
method: 6, // 压缩方法(0-6),数值越大,压缩率越高但速度变慢
},
pngquant: {
quality: [0.8, 0.9], // PNG 质量范围
speed: 4, // 压缩速度(1-10),数值越大速度越快但压缩率降低
},
disable: !isBuild, // 仅在生产环境启用
/** 是否在控制台输出压缩结果 */
verbose: true,
})
]
}
})
四、参数解析
4.1、gifsicle(GIF 优化)
参数 |
作用 |
取值范围 |
推荐值 |
interlaced |
是否启用隔行扫描 |
true/false |
true |
optimizationLevel |
压缩级别 |
0-3 |
3 |
4.2、optipng(PNG 优化)
参数 |
作用 |
取值范围 |
推荐值 |
optimizationLevel |
压缩级别 |
0-7 |
5 |
4.3、mozjpeg(JPG 优化)
参数 |
作用 |
取值范围 |
推荐值 |
quality |
质量 |
0-100 |
80 |
progressive |
渐进式加载 |
true/false |
true |
smooth |
平滑度 |
0-100 |
2 |
4.4、svgo(SVG 优化)
参数 |
作用 |
取值范围 |
推荐值 |
removeViewBox |
保留 viewBox 防止 SVG 变形 |
true/false |
false |
removeEmptyAttrs |
移除空属性 |
true/false |
true |
convertColors |
颜色转换 |
{ currentColor: true } |
{ currentColor: true } |
4.5、webp(WebP 优化)
参数 |
作用 |
取值范围 |
推荐值 |
quality |
质量 |
0-100 |
80 |
lossless |
是否无损压缩 |
true/false |
false |
method |
压缩方法(数值越大,压缩率越高但速度变慢) |
0-6 |
6 |
4.6、pngquant(PNG 量化)
参数 |
作用 |
取值范围 |
推荐值 |
quality |
质量范围 |
[min, max] (0-1) |
[0.6, 0.8] |
speed |
压缩速度,越大速度越快但压缩率降低 |
1-10 |
4 |
4.7、其它配置
参数 |
作用 |
取值范围 |
推荐值 |
svgoOptions.multipass |
多次优化 SVG |
true/false |
true |
cache |
开启缓存,加快二次构建 |
true/false |
true |
filter |
过滤文件路径,如跳过 node_modules 目录 |
(source: string) => boolean |
!source.includes('node_modules') |
disable |
仅在生产环境启用 |
true/false |
!isBuild |
五、总结
使用 vite-plugin-imagemin
,可以实现:
- ✅ 自动化图片压缩,提高页面加载速度
- ✅ 支持 PNG、JPG、GIF、SVG、WebP 多种格式
- ✅ 仅在生产环境启用,开发环境不受影响
- ✅ 结合缓存功能,提高构建速度
希望这篇文章能帮助你更好地优化 Vite 项目的图片资源!🚀