Vue3进行打包配置的优化指南
作者:AI砖家
随着 Vue3 项目的业务迭代,打包体积过大、首屏加载缓慢逐渐成为影响用户体验的核心问题。本文将详细介绍如何通过精细化的打包配置,实现代码分包、剔除冗余 Console 日志,并结合最佳实践,帮助你将项目打包体积缩减 70%,首屏加载速度提升 60%。
一、优化前的准备:性能诊断
在开始优化之前,我们需要先定位性能瓶颈。推荐使用打包分析工具可视化查看各模块的体积占比。
1.1 安装打包分析插件
# Vite 项目 npm install rollup-plugin-visualizer -D # Webpack 项目 npm install webpack-bundle-analyzer -D
1.2 配置与使用
配置完成后执行 npm run build,会自动生成一个可视化报告文件,帮助你快速定位大文件。

二、Vite 构建工具配置
对于使用 Vite 创建的 Vue3 项目,我们主要通过修改 vite.config.ts 来实现打包优化。
2.1 代码分包(Code Splitting)
Vite 默认的打包策略会将所有代码打包成几个大块,我们可以通过 manualChunks 自定义分包规则,将不常变动的第三方库单独打包,利用浏览器缓存。
2.1.1 基础分包:提取所有第三方库
最简单的配置是将所有 node_modules 中的依赖打包成一个 vendor.js 文件。
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
build: {
rollupOptions: {
output: {
// 自定义分包
manualChunks: (id) => {
// 将 node_modules 中的代码单独打包成 vendor.js
if (id.includes('node_modules')) {
return 'vendor'
}
},
// 自定义输出文件名
entryFileNames: `assets/js/[name]-[hash].js`,
chunkFileNames: `assets/js/[name]-[hash].js`,
assetFileNames: `assets/[ext]/[name]-[hash].[ext]`,
}
}
}
})
2.1.2 精细化分包:拆分大体积依赖
当项目依赖较多时,vendor.js 本身也会变得很大。我们可以进一步将大体积的依赖单独拆分。
// vite.config.ts
build: {
rollupOptions: {
output: {
manualChunks: {
// 将 Vue 全家桶打包在一起
'vue-vendor': ['vue', 'vue-router', 'pinia'],
// 将 UI 库单独打包
'ui-vendor': ['element-plus'],
// 将图表库单独打包
'echarts-vendor': ['echarts']
}
}
}
}
2.1.3 动态分包策略
更灵活的方式是根据模块路径动态判断:
manualChunks: (id) => {
if (id.includes('echarts')) {
return 'echarts-vendor'
}
if (id.includes('element-plus')) {
return 'ui-vendor'
}
if (id.includes('node_modules')) {
return 'vendor'
}
}
2.2 过滤 Console 与 Debugger
在生产环境中,我们通常需要移除开发时留下的 console.log 和 debugger 语句。Vite 提供了两种压缩方式:esbuild 和 terser。
2.2.1 使用 Esbuild 快速移除(推荐)
Esbuild 是 Vite 默认的压缩工具,速度极快。
// vite.config.ts
import { defineConfig, loadEnv } from 'vite'
export default defineConfig(({ mode }) => {
// 判断是否为生产环境
const isProduction = mode === 'production'
return {
esbuild: {
// 仅在生产环境移除 console 和 debugger
drop: isProduction ? ["console", "debugger"] : [],
}
}
})
注意:drop: ["console"] 会移除所有的 console 方法,包括 console.warn 和 console.error。
2.2.2 使用 Terser 精细化控制
如果你只想移除 console.log 而保留 console.error,可以使用 Terser。
首先安装依赖:
npm i terser -D
然后配置:
// vite.config.ts
build: {
minify: 'terser', // 启用 terser 压缩
terserOptions: {
compress: {
// 只删除 console.log
pure_funcs: ['console.log'],
// 删除所有 console
// drop_console: true,
// 删除 debugger
drop_debugger: true,
}
}
}
2.3 Vite 完整配置示例
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { visualizer } from 'rollup-plugin-visualizer'
import viteCompression from 'vite-plugin-compression'
import { resolve } from 'path'
export default defineConfig(({ mode }) => {
const isProduction = mode === 'production'
return {
resolve: {
alias: {
'@': resolve(__dirname, 'src')
}
},
esbuild: {
drop: isProduction ? ["console", "debugger"] : []
},
plugins: [
vue(),
// 打包分析
visualizer({
open: true,
gzipSize: true,
brotliSize: true
}),
// Gzip 压缩
viteCompression({
algorithm: 'gzip',
threshold: 10240, // 10KB
})
],
build: {
sourcemap: !isProduction,
rollupOptions: {
output: {
manualChunks: (id) => {
if (id.includes('echarts')) {
return 'echarts-vendor'
}
if (id.includes('element-plus')) {
return 'ui-vendor'
}
if (id.includes('node_modules')) {
return 'vendor'
}
},
entryFileNames: `assets/js/[name]-[hash].js`,
chunkFileNames: `assets/js/[name]-[hash].js`,
assetFileNames: `assets/[ext]/[name]-[hash].[ext]`,
}
}
}
}
})
三、Webpack / Vue-CLI 构建工具配置
对于使用 Vue-CLI 创建的传统 Webpack 项目,我们通过修改 vue.config.js 来进行配置。
3.1 代码分包(splitChunks)
Webpack 通过 optimization.splitChunks 来实现代码分割。
// vue.config.js
module.exports = {
configureWebpack: {
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
cacheGroups: {
// 提取公共模块
common: {
name: 'chunk-common',
minChunks: 2,
minSize: 1,
priority: 10,
chunks: 'all',
reuseExistingChunk: true
},
// 提取第三方库
vendor: {
name: 'chunk-vendors',
test: /[\\/]node_modules[\\/]/,
priority: 20,
chunks: 'all',
reuseExistingChunk: true
},
// 单独拆分 Element Plus
elementUI: {
name: 'chunk-element-plus',
test: /[\\/]node_modules[\\/]element-plus[\\/]/,
priority: 30,
chunks: 'all'
}
}
}
}
}
}
3.2 过滤 Console 与 Debugger
同样,我们可以通过配置 Terser 来移除生产环境的日志。
// vue.config.js
const TerserPlugin = require('terser-webpack-plugin')
module.exports = {
configureWebpack: {
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true, // 移除所有console
drop_debugger: true, // 移除debugger
// pure_funcs: ['console.log'] // 仅移除log
}
}
})
]
}
}
}
或者使用 chainWebpack 链式调用:
// vue.config.js
chainWebpack: config => {
if (process.env.NODE_ENV === 'production') {
// 移除console
config.optimization.minimize(true)
.minimizer('terser')
.tap(args => {
let { terserOptions } = args[0]
terserOptions.compress.drop_console = true
terserOptions.compress.drop_debugger = true
return args
})
}
}
四、进阶优化策略

4.1 开启 Gzip / Brotli 压缩
开启 Gzip 压缩可以将资源体积减少 60%-80%。
// vite.config.ts
import viteCompression from 'vite-plugin-compression'
plugins: [
// Gzip
viteCompression({
algorithm: 'gzip',
threshold: 10240,
deleteOriginFile: false
}),
// Brotli (压缩率更高)
viteCompression({
algorithm: 'brotliCompress',
threshold: 10240
})
]
注意:开启后需要在 Nginx 或 CDN 上配置对应的响应头,让服务器返回压缩后的文件。
4.2 路由懒加载
将路由组件懒加载,拆分 chunk,首屏只加载必要的代码。
// router/index.js
const routes = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue') // 懒加载
},
{
path: '/about',
name: 'About',
component: () => import('@/views/About.vue')
}
]
4.3 CDN 外部化依赖
将 Vue、Element Plus 等不常更新的库通过 CDN 引入,不参与本地打包。
// vite.config.ts
build: {
rollupOptions: {
external: ['vue', 'vue-router', 'element-plus'],
output: {
globals: {
vue: 'Vue',
'vue-router': 'VueRouter',
'element-plus': 'ElementPlus'
}
}
}
}
然后在 index.html 中引入 CDN 链接。
4.4 Tree Shaking 摇树优化
确保项目使用 ES Module,在 package.json 中添加:
{
"sideEffects": false
}
这会告诉打包工具所有模块都没有副作用,可以安全地删除未使用的代码。
五、优化效果验证
经过以上配置优化后,一个典型的中后台管理系统可以达到以下效果:
| 指标 | 优化前 | 优化后 | 提升幅度 |
|---|---|---|---|
| 打包总体积 | 2.6 MB | 500 KB | 缩减 80% |
| 首屏加载时间 | 3.2 s | 1.3 s | 提升 60% |
| Vendor Chunk | 1.8 MB | 200 KB | 缩减 89% |
| Lighthouse 评分 | 62 分 | 94 分 | 提升 51% |
六、避坑指南
- 不要过度分包:分包越多,网络请求越多。对于小型项目,保持默认配置即可。
- 环境区分:移除 Console 仅在生产环境生效,开发环境保留方便调试。
- Source Map:生产环境建议关闭
sourcemap,除非你需要线上错误监控。 - 缓存策略:分包后配合文件 Hash,利用浏览器长效缓存,大幅提升二次访问速度。
通过以上配置,你的 Vue3 项目将拥有极致的加载性能和打包效率,为用户带来秒开的体验。
到此这篇关于Vue3进行打包配置的优化指南的文章就介绍到这了,更多相关Vue3打包配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
