node version: >= 12.0.0
vite version: >=2.0.0
yarn add vite-plugin-imagemin -D
or
npm i vite-plugin-imagemin -D
因为imagemin在国内不好安装,所以提供几个解决方案
"resolutions": {
"bin-wrapper": "npm:bin-wrapper-china"
}
199.232.4.133 raw.githubusercontent.com
import viteImagemin from 'vite-plugin-imagemin'
import { join, resolve } from 'path'
import vue from '@vitejs/plugin-vue'
export default ({ mode }: ConfigEnv): UserConfigExport => {
return defineConfig({
plugins: [
vue(),
viteCompression({
ext: '.gz',
algorithm: 'gzip',
deleteOriginFile: false
})
viteImagemin({
gifsicle: {
optimizationLevel: 7,
interlaced: false
},
optipng: {
optimizationLevel: 7
},
mozjpeg: {
quality: 20
},
pngquant: {
quality: [0.8, 0.9],
speed: 4
},
svgo: {
plugins: [
{
name: 'removeViewBox'
},
{
name: 'removeEmptyAttrs',
active: false
}
]
}
})
],
resolve: {
alias: [{ find: '@', replacement: resolve(__dirname, './src') }]
},
build: {
target: 'es2015',
outDir: 'dist',
rollupOptions: {
output: {
manualChunks: {
echarts: ['echarts']
}
}
}
// assetsDir: 'assets'
}
})
}
每次打包都会走一遍图片压缩的流程,在你改动很小的时候进行npm run build的时候,都会再次压缩,需要长时间等待
优化方案
在打包前运行脚本图片压缩npm run build:img,压缩一次后记录图片,然后记录时间戳,压缩后修改原文件,再进行build。当你你二次打包的时候
进行对比,在范围内跳过图片压缩
第二次打包时间⬇️
秒过 nice 图片大小不变
原本 dist -> 35m
打包 dist -> 12m