it编程 > 编程语言 > Javascript

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

5人参与 2025-04-24 Javascript

一、基础性能优化配置(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等服务器直接发送压缩包

业务场景

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'
      }
    }
  }
}

分包规则

业务场景

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环境需要开启
    }
  }
}

调试技巧

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
  }
}

模式说明

二、进阶优化方案

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');
}

五、注意事项

压缩兼容性

缓存策略

安全优化

到此这篇关于vue3+vite4项目进行性能优化的配置方案的文章就介绍到这了,更多相关vue3 vite4性能优化内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

JavaScript判断页面滚动方向的三种方法

04-24

vue项目在运行npm run build时卡住不动问题及解决方案

04-24

前端JavaScript跳转页面的几种方法以及区别详解

04-24

如何用 Deepseek 写的uniapp血型遗传查询工具

04-24

JavaScript实现字符串转字符数组的两种方式

04-24

JavaScript中$.ajax()最新用法举例详解

04-24

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论