Vite 对 Vue 项目的性能优化
Vite 本身已经对 Vue 项目做了很多优化,但在大型 Vue 项目中,仍然可以通过依赖优化、懒加载、代码分割、构建优化等方法提升性能。以下是一些关键优化点:
1️⃣ 依赖优化
🔹 1. 预构建依赖
Vite 使用 esbuild 进行依赖预构建,但如果依赖过多或编译慢,可以手动优化:
✅ 方法:在 vite.config.js 里配置 optimizeDeps
export default defineConfig({
optimizeDeps: {
include: ['lodash-es', 'dayjs'], // 预构建常用库,避免运行时编译
exclude: ['some-large-lib'], // 排除体积大但不常用的库
},
});
📌 适用场景:
- 项目中
node_modules依赖较多,导致 Vite 启动慢。
🔹 2. 手动优化 node_modules 依赖
某些依赖体积太大,Vite 不会自动优化,可以使用 pre-bundling 预构建:
vite optimize
这样可以加速首次加载。
2️⃣ 组件懒加载
🔹 1. 路由懒加载
避免一次性加载所有页面,按需加载:
import { createRouter, createWebHistory } from 'vue-router';
const routes = [
{ path: '/', component: () => import('@/views/Home.vue') }, // 懒加载
{ path: '/about', component: () => import('@/views/About.vue') },
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
📌 适用场景:
- Vue 项目页面较多,防止主包过大。
🔹 2. 组件懒加载
某些组件不常使用,可以使用 defineAsyncComponent:
import { defineAsyncComponent } from 'vue';
const AsyncComponent = defineAsyncComponent(() =>
import('@/components/HeavyComponent.vue')
);
📌 适用场景:
- 页面内的部分组件不常用,例如弹窗、富文本编辑器等。
3️⃣ 代码分割
🔹 1. Vite 内置代码分割
Vite 默认使用 Rollup 进行代码分割,避免单一 bundle.js 过大,影响首屏加载。
但我们可以手动优化:
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
if (id.includes('vue')) return 'vue';
if (id.includes('lodash')) return 'lodash';
return 'vendor'; // 其他依赖归为 vendor
}
},
},
},
},
});
📌 适用场景:
vendor:公共依赖(Vue、Pinia、Axios)。lodash:某些大型依赖单独打包,避免主包过大。
🔹 2. 静态资源 CDN
一些**大体积库(如 Vue、Axios、Lodash)**可以使用 CDN 加载,减少 dist 体积:
export default defineConfig({
build: {
rollupOptions: {
external: ['vue', 'axios', 'lodash'],
},
},
plugins: [
{
name: 'external-cdn',
transformIndexHtml(html) {
return html.replace(
'</head>',
`<script src="https://cdn.jsdelivr.net/npm/vue@3"></script>
<script src="https://cdn.jsdelivr.net/npm/axios@0.27.2"></script>
</head>`
);
},
},
],
});
📌 适用场景:
- Vue 组件库:Element Plus、Ant Design Vue、Naive UI 体积大,可以走 CDN。
4️⃣ 图片与资源优化
🔹 1. 图片懒加载
在 Vue 中使用 v-lazy,减少首屏资源加载:
<img v-lazy="'/images/big-image.jpg'" />
📌 适用场景:
- 博客/电商类项目,图片较多时可减少页面加载压力。
🔹 2. 图片格式优化
-
优先使用 WebP 格式,相比 JPG/PNG 体积小 30%~50%。
-
压缩大图片:
npm install imagemin imagemin-mozjpeg imagemin-pngquant --save-dev然后:
import imagemin from 'imagemin'; import imageminMozjpeg from 'imagemin-mozjpeg'; import imageminPngquant from 'imagemin-pngquant'; (async () => { await imagemin(['public/images/*.{jpg,png}'], { destination: 'dist/images', plugins: [imageminMozjpeg({ quality: 75 }), imageminPngquant({ quality: [0.6, 0.8] })], }); })();
📌 适用场景:
- 需要大量图片资源的网站。
5️⃣ 构建优化
🔹 1. 生产环境启用 gzip 压缩
Vite 不会自动开启 gzip,可以安装 vite-plugin-compression:
npm install vite-plugin-compression --save-dev
然后在 vite.config.js 里启用:
import compression from 'vite-plugin-compression';
export default defineConfig({
plugins: [compression()],
});
📌 适用场景:
- 服务器开启 gzip 支持(如 Nginx)。
🔹 2. 使用 PWA(渐进式 Web 应用)
可以使用 vite-plugin-pwa:
npm install vite-plugin-pwa --save-dev
然后:
import { VitePWA } from 'vite-plugin-pwa';
export default defineConfig({
plugins: [
VitePWA({
registerType: 'autoUpdate',
manifest: {
name: 'My Vite App',
short_name: 'ViteApp',
start_url: '/',
display: 'standalone',
background_color: '#ffffff',
theme_color: '#42b883',
},
}),
],
});
📌 适用场景:
- 离线应用、小程序、PWA 项目。
🔚 总结
| 优化点 | 方法 |
|---|---|
| 依赖优化 | optimizeDeps 预构建,排除大依赖 |
| 组件懒加载 | import() 动态导入组件 |
| 代码分割 | manualChunks 切分 Vue、Axios、Lodash |
| 静态资源优化 | 使用 CDN 加载 Vue、Element Plus |
| 图片优化 | WebP 格式、懒加载、imagemin 压缩 |
| 构建优化 | Gzip 压缩、PWA |
✅ 经过这些优化,Vite + Vue 项目可以更快速启动、降低包体积、提升用户体验 🚀