• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    Vue3+Vite4项目进行性能优化的配置方案

    发布者: 土豆服务器 | 发布时间: 2025-6-14 15:29| 查看数: 177| 评论数: 0|帖子模式

    一、基础性能优化配置(vite.config.ts)


    1. Gzip 压缩加速
    1. import viteCompression from 'vite-plugin-compression';

    2. // plugins 数组中添加
    3. viteCompression({
    4.   verbose: true, // 显示压缩日志
    5.   threshold: 10240, // 超过10kb的文件才压缩
    6.   algorithm: 'gzip', // 算法可选brotliCompress
    7.   ext: '.gz',
    8.   deleteOriginFile: false // 根据服务器配置决定是否删除源文件
    9. })
    复制代码
    作用:预生成.gz文件,Nginx等服务器直接发送压缩包
    业务场景

    • 高并发场景建议开启(需服务器配合)
    • 静态资源托管CDN时建议删除源文件(
      1. deleteOriginFile: true
      复制代码


    2. 资源压缩优化
    1. import { viteStaticCopy } from 'vite-plugin-static-copy';

    2. // 图片压缩(需安装 vite-plugin-imagemin)
    3. import viteImagemin from 'vite-plugin-imagemin';

    4. export default {
    5.   plugins: [
    6.     viteImagemin({
    7.       gifsicle: { optimizationLevel: 7 },
    8.       optipng: { optimizationLevel: 7 },
    9.       mozjpeg: { quality: 65 },
    10.       pngquant: { quality: [0.65, 0.9] },
    11.       svgo: {
    12.         plugins: [{ name: 'removeViewBox' }, { name: 'cleanupIDs' }]
    13.       }
    14.     }),
    15.     // 静态资源复制插件
    16.     viteStaticCopy({
    17.       targets: [
    18.         { src: 'public/static-assets', dest: 'assets' }
    19.       ]
    20.     })
    21.   ]
    22. }
    复制代码
    作用

    • 图片压缩:降低图片体积(适合中大型图片资源项目)
    • 静态资源分类:通过
      1. viteStaticCopy
      复制代码
      分离高频更新资源
    业务场景

    • 图片为主的展示型网站必须开启
    • 管理后台类项目可酌情降低压缩率(
      1. quality: 75
      复制代码


    3. 分包策略
    1. export default {
    2.   build: {
    3.     rollupOptions: {
    4.       output: {
    5.         manualChunks: (id) => {
    6.           if (id.includes('node_modules')) {
    7.             if (id.includes('vue')) return 'vue-core';
    8.             if (id.includes('lodash')) return 'lodash';
    9.             return 'vendor';
    10.           }
    11.           if (id.includes('src/components')) return 'components';
    12.         },
    13.         chunkFileNames: 'js/[name]-[hash].js'
    14.       }
    15.     }
    16.   }
    17. }
    复制代码
    分包规则

      1. vue-core
      复制代码
      :Vue核心库单独分包
      1. vendor
      复制代码
      :第三方依赖包
      1. components
      复制代码
      :业务组件独立分包
    业务场景

    • 多入口应用:按路由入口分包
    • 组件库项目:按功能模块分包

    4. 按需加载
    1. // 路由配置示例
    2. const routes = [
    3.   {
    4.     path: '/dashboard',
    5.     component: () => import(/* webpackChunkName: "dashboard" */ '@/views/Dashboard.vue')
    6.   }
    7. ]
    复制代码
    实现方式
    路由级:动态
    1. import()
    复制代码
    语法
    组件级:
    1. defineAsyncComponent
    复制代码
    UI库按需加载(以Element Plus为例):
    1. import Components from 'unplugin-vue-components/vite'
    2. import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

    3. Components({
    4.   resolvers: [ElementPlusResolver()],
    5.   dts: true // 生成类型声明文件
    6. })
    复制代码
    5. 热更新配置
    1. export default {
    2.   server: {
    3.     hmr: {
    4.       overlay: true, // 显示错误覆盖层
    5.       protocol: 'ws',
    6.       host: 'localhost',
    7.       port: 3000
    8.     },
    9.     watch: {
    10.       usePolling: true // Docker环境需要开启
    11.     }
    12.   }
    13. }
    复制代码
    调试技巧

    • 开发环境禁用缓存:
      1. server.headers
      复制代码
      设置
      1. Cache-Control: no-store
      复制代码
    • 跨设备开发:设置
      1. host: '0.0.0.0'
      复制代码

    6. 路径别名配置
    1. import path from 'path';

    2. export default {
    3.   resolve: {
    4.     alias: {
    5.       '@': path.resolve(__dirname, './src'),
    6.       '#': path.resolve(__dirname, './types')
    7.     }
    8.   }
    9. }
    复制代码
    配套设置
    1. // tsconfig.json
    2. {
    3.   "compilerOptions": {
    4.     "paths": {
    5.       "@/*": ["./src/*"],
    6.       "#/*": ["./types/*"]
    7.     }
    8.   }
    9. }
    复制代码
    7. Sourcemap 策略
    1. export default {
    2.   build: {
    3.     sourcemap: process.env.NODE_ENV === 'production' ? 'hidden' : true
    4.   }
    5. }
    复制代码
    模式说明

    • 开发环境:完整sourcemap
    • 生产环境:
      1. hidden-source-map
      复制代码
      (仅生成.map文件不上传)
    • 错误监控:接入Sentry时需开启sourcemap上传

    二、进阶优化方案


    1. CDN 加速
    1. import { createHtmlPlugin } from 'vite-plugin-html';

    2. export default {
    3.   plugins: [
    4.     createHtmlPlugin({
    5.       inject: {
    6.         data: {
    7.           cdnVue: '<script src="https://cdn.jsdelivr.net/npm/vue@3"></script>'
    8.         }
    9.       }
    10.     })
    11.   ],
    12.   build: {
    13.     rollupOptions: {
    14.       external: ['vue', 'vue-router'],
    15.       output: {
    16.         globals: {
    17.           vue: 'Vue',
    18.           'vue-router': 'VueRouter'
    19.         }
    20.       }
    21.     }
    22.   }
    23. }
    复制代码
    2. 预加载优化
    1. // vite.config.ts
    2. export default {
    3.   build: {
    4.     rollupOptions: {
    5.       output: {
    6.         manualChunks: {
    7.           // ...其他配置
    8.         },
    9.         assetFileNames: 'assets/[ext]/[name]-[hash][extname]'
    10.       }
    11.     }
    12.   }
    13. }

    14. // index.html 添加预加载
    15. <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)
    示例配置:
    1. build: {
    2.   assetsInlineLimit: 4096, // 4kb以下资源转base64
    3. }
    复制代码
    场景2:后台管理系统

    配置重点:
    1. 按功能模块分包
    2. 保留详细sourcemap便于调试
    3. 开发环境优化HMR速度
    示例配置:
    1. server: {
    2.   watch: {
    3.     ignored: ['!**/node_modules/your-package/**'] // 忽略无关模块监听
    4.   }
    5. }
    复制代码
    场景3:移动端H5应用

    配置重点:
    1. 首屏资源内联(critical CSS)
    2. 图片格式优先使用WebP
    3. 开启SSR或预渲染
    示例配置:
    1. css: {
    2.   postcss: {
    3.     plugins: [
    4.       require('postcss-critical-css')({
    5.         outputPath: 'critical'
    6.       })
    7.     ]
    8.   }
    9. }
    复制代码
    四、调试与分析工具

    打包分析
    1. npm install rollup-plugin-visualizer -D

    2. // vite.config.ts
    3. import { visualizer } from 'rollup-plugin-visualizer';

    4. plugins: [visualizer({ open: true })]
    复制代码
    性能检测
    1. // main.ts
    2. import { performance } from 'perf_hooks';
    3. if (import.meta.env.DEV) {
    4.   performance.mark('app-start');
    5. }
    复制代码
    五、注意事项

    压缩兼容性

    • 确保服务器正确配置
      1. Content-Encoding
      复制代码
      响应头
    • 旧版浏览器需检测是否支持Brotli
    缓存策略

    • 修改文件名哈希规则(
      1. build.rollupOptions.output.[assetFileNames|entryFileNames]
      复制代码

    • 使用
      1. manifest.json
      复制代码
      管理版本号
    安全优化

    • 生产环境禁用sourcemap
    • 设置
      1. build.minify: 'terser'
      复制代码
      并配置混淆参数
    到此这篇关于Vue3+Vite4项目进行性能优化的配置方案的文章就介绍到这了,更多相关Vue3 Vite4性能优化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    来源:https://www.jb51.net/javascript/340034rgh.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表