一、基础性能优化配置(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时建议删除源文件()
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' }
- ]
- })
- ]
- }
复制代码 作用:
- 图片压缩:降低图片体积(适合中大型图片资源项目)
- 静态资源分类:通过分离高频更新资源
业务场景:
- 图片为主的展示型网站必须开启
- 管理后台类项目可酌情降低压缩率()
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核心库单独分包
- :第三方依赖包
- :业务组件独立分包
业务场景:
- 多入口应用:按路由入口分包
- 组件库项目:按功能模块分包
4. 按需加载
- // 路由配置示例
- const routes = [
- {
- path: '/dashboard',
- component: () => import(/* webpackChunkName: "dashboard" */ '@/views/Dashboard.vue')
- }
- ]
复制代码 实现方式:
路由级:动态语法
组件级: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环境需要开启
- }
- }
- }
复制代码 调试技巧:
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
- 生产环境:(仅生成.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');
- }
复制代码 五、注意事项
压缩兼容性:
- 确保服务器正确配置响应头
- 旧版浏览器需检测是否支持Brotli
缓存策略:
- 修改文件名哈希规则(
- build.rollupOptions.output.[assetFileNames|entryFileNames]
复制代码 )
- 使用管理版本号
安全优化:
- 生产环境禁用sourcemap
- 设置并配置混淆参数
到此这篇关于Vue3+Vite4项目进行性能优化的配置方案的文章就介绍到这了,更多相关Vue3 Vite4性能优化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源:https://www.jb51.net/javascript/340034rgh.htm
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |
|