【Vite】打包优化
一、Vite 打包优化思路
-
按需引入(Tree Shaking)
- 避免全量引入库(如 UI 库、工具库)
// lodash 按需导入 import debounce from 'lodash/debounce';
-
配合插件:
unplugin-vue-components
:UI 组件自动按需导入unplugin-auto-import
:函数按需导入
-
压缩与去除日志
- 配置 Terser 压缩代码
- 去掉
console.log
和debugger
// vite.config.js build: {terserOptions: {compress: {drop_console: true,drop_debugger: true}} }
-
静态资源优化
- 图片压缩、SVG 精简
- 使用
vite-plugin-compression
打包成 gzip 或 brotli
-
依赖预打包(Pre-Bundling)
- Vite 默认使用 esbuild 对依赖预打包,加快冷启动
- 对大体积依赖,可以手动
optimizeDeps.include
-
开启多线程/缓存
- Vite 默认 esbuild 很快
- 配合 CI/CD 缓存 node_modules,减少二次打包时间
二、代码分包(Code Splitting / Lazy Loading)
-
路由懒加载
- 按需加载页面组件,减少首屏包体积
import { createRouter, createWebHistory } from 'vue-router';const Home = () => import('@/views/Home.vue'); const About = () => import('@/views/About.vue');const routes = [{ path: '/', component: Home },{ path: '/about', component: About } ];const router = createRouter({history: createWebHistory(),routes });
-
动态导入(Dynamic Import)
- 在业务逻辑中按需加载模块
button.addEventListener('click', async () => {const { heavyFunction } = await import('./heavyModule.js');heavyFunction(); });
-
手动分包(Rollup 配置)
- Vite 底层使用 Rollup,可以自定义打包策略
// vite.config.js build: {rollupOptions: {output: {manualChunks(id) {if (id.includes('node_modules')) {return 'vendor'; // 第三方库单独打包}if (id.includes('charts')) {return 'charts'; // 特定模块单独打包}}}} }
-
CSS 分包
- Vite 默认将 CSS 提取为单独文件
- 可以按路由拆分 CSS,减少首屏加载
三、总结
“在 Vite 项目中,我主要做了以下优化:
- 按需引入组件和工具库,减少首屏打包体积;
- 使用 Terser 去掉 console/debugger,并对静态资源压缩;
- 路由组件和业务模块使用动态导入,实现懒加载和代码分包;
- 配置 Rollup manualChunks,将第三方库和大体积模块单独打包,提升缓存命中率;
这样既优化了首屏加载速度,也提高了整体构建性能。”