一、基础性能优化配置(vite.config.ts)
1. gzip 压缩加速
import vitecompression from 'vite-plugin-compression'; // plugins 数组中添加 vitecompression({ verbose: true, // 显示压缩日志 threshold: 10240, // 超过10kb的文件才压缩 algorithm: 'gzip', // 算法可选brotlicompress ext: '.gz', deleteoriginfile: false // 根据服务器配置决定是否删除源文件 })
作用:预生成.gz文件,nginx等服务器直接发送压缩包
业务场景:
- 高并发场景建议开启(需服务器配合)
- 静态资源托管cdn时建议删除源文件(
deleteoriginfile: true
)
2. 资源压缩优化
import { vitestaticcopy } from 'vite-plugin-static-copy'; // 图片压缩(需安装 vite-plugin-imagemin) import viteimagemin from 'vite-plugin-imagemin'; export default { plugins: [ viteimagemin({ gifsicle: { optimizationlevel: 7 }, optipng: { optimizationlevel: 7 }, mozjpeg: { quality: 65 }, pngquant: { quality: [0.65, 0.9] }, svgo: { plugins: [{ name: 'removeviewbox' }, { name: 'cleanupids' }] } }), // 静态资源复制插件 vitestaticcopy({ targets: [ { src: 'public/static-assets', dest: 'assets' } ] }) ] }
作用:
- 图片压缩:降低图片体积(适合中大型图片资源项目)
- 静态资源分类:通过
vitestaticcopy
分离高频更新资源
业务场景:
- 图片为主的展示型网站必须开启
- 管理后台类项目可酌情降低压缩率(
quality: 75
)
3. 分包策略
export default { build: { rollupoptions: { output: { manualchunks: (id) => { if (id.includes('node_modules')) { if (id.includes('vue')) return 'vue-core'; if (id.includes('lodash')) return 'lodash'; return 'vendor'; } if (id.includes('src/components')) return 'components'; }, chunkfilenames: 'js/[name]-[hash].js' } } } }
分包规则:
vue-core
:vue核心库单独分包vendor
:第三方依赖包components
:业务组件独立分包
业务场景:
- 多入口应用:按路由入口分包
- 组件库项目:按功能模块分包
4. 按需加载
// 路由配置示例 const routes = [ { path: '/dashboard', component: () => import(/* webpackchunkname: "dashboard" */ '@/views/dashboard.vue') } ]
实现方式:
路由级:动态import()
语法
组件级:defineasynccomponent
ui库按需加载(以element plus为例):
import components from 'unplugin-vue-components/vite' import { elementplusresolver } from 'unplugin-vue-components/resolvers' components({ resolvers: [elementplusresolver()], dts: true // 生成类型声明文件 })
5. 热更新配置
export default { server: { hmr: { overlay: true, // 显示错误覆盖层 protocol: 'ws', host: 'localhost', port: 3000 }, watch: { usepolling: true // docker环境需要开启 } } }
调试技巧:
- 开发环境禁用缓存:
server.headers
设置cache-control: no-store
- 跨设备开发:设置
host: '0.0.0.0'
6. 路径别名配置
import path from 'path'; export default { resolve: { alias: { '@': path.resolve(__dirname, './src'), '#': path.resolve(__dirname, './types') } } }
配套设置:
// tsconfig.json { "compileroptions": { "paths": { "@/*": ["./src/*"], "#/*": ["./types/*"] } } }
7. sourcemap 策略
export default { build: { sourcemap: process.env.node_env === 'production' ? 'hidden' : true } }
模式说明:
- 开发环境:完整sourcemap
- 生产环境:
hidden-source-map
(仅生成.map文件不上传) - 错误监控:接入sentry时需开启sourcemap上传
二、进阶优化方案
1. cdn 加速
import { createhtmlplugin } from 'vite-plugin-html'; export default { plugins: [ createhtmlplugin({ inject: { data: { cdnvue: '<script src="https://cdn.jsdelivr.net/npm/vue@3"></script>' } } }) ], build: { rollupoptions: { external: ['vue', 'vue-router'], output: { globals: { vue: 'vue', 'vue-router': 'vuerouter' } } } } }
2. 预加载优化
// vite.config.ts export default { build: { rollupoptions: { output: { manualchunks: { // ...其他配置 }, assetfilenames: 'assets/[ext]/[name]-[hash][extname]' } } } } // index.html 添加预加载 <link rel="preload" href="/assets/fonts/iconfont.woff2" rel="external nofollow" as="font" type="font/woff2" crossorigin>
三、业务场景配置策略
场景1:高并发门户网站
配置重点:
1. 开启gzip + brotli双重压缩
2. 所有静态资源上传cdn
3. 使用http2服务器推送
4. 配置强缓存策略(cache-control: public, max-age=31536000)
示例配置:
build: { assetsinlinelimit: 4096, // 4kb以下资源转base64 }
场景2:后台管理系统
配置重点:
1. 按功能模块分包
2. 保留详细sourcemap便于调试
3. 开发环境优化hmr速度
示例配置:
server: { watch: { ignored: ['!**/node_modules/your-package/**'] // 忽略无关模块监听 } }
场景3:移动端h5应用
配置重点:
1. 首屏资源内联(critical css)
2. 图片格式优先使用webp
3. 开启ssr或预渲染
示例配置:
css: { postcss: { plugins: [ require('postcss-critical-css')({ outputpath: 'critical' }) ] } }
四、调试与分析工具
打包分析:
npm install rollup-plugin-visualizer -d // vite.config.ts import { visualizer } from 'rollup-plugin-visualizer'; plugins: [visualizer({ open: true })]
性能检测:
// main.ts import { performance } from 'perf_hooks'; if (import.meta.env.dev) { performance.mark('app-start'); }
五、注意事项
压缩兼容性:
- 确保服务器正确配置
content-encoding
响应头 - 旧版浏览器需检测是否支持brotli
缓存策略:
- 修改文件名哈希规则(
build.rollupoptions.output.[assetfilenames|entryfilenames]
) - 使用
manifest.json
管理版本号
安全优化:
- 生产环境禁用sourcemap
- 设置
build.minify: 'terser'
并配置混淆参数
到此这篇关于vue3+vite4项目进行性能优化的配置方案的文章就介绍到这了,更多相关vue3 vite4性能优化内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论