Vue项目代码分割与懒加载:Webpack与Vite的极致优化实践
Vue项目代码分割与懒加载:Webpack与Vite的极致优化实践
一、首屏加载瓶颈分析
1.1 性能指标
- FCP (First Contentful Paint)
- LCP (Largest Contentful Paint)
- JavaScript执行阻塞时间
1.2 问题根源
- 单文件打包导致的超大bundle
- 同步加载未使用的组件
- 第三方库未合理拆分
二、代码分割核心原理
2.1 动态导入(Dynamic Import)
const Home = () => import('./views/Home.vue')
2.2 Webpack分块策略
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
}
}
}
}
}
2.3 Vite的ESM原生支持
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
return 'vendor'
}
}
}
}
}
})
三、路由级懒加载
3.1 Vue Router配置
const routes = [
{
path: '/dashboard',
component: () => import( './views/Dashboard.vue')
}
]
3.2 预加载策略
<link rel="preload" href="/assets/dashboard.js" as="script">
四、组件级懒加载
4.1 异步组件
<template>
<Suspense>
<template #default>
<AsyncComponent />
</template>
<template #fallback>
<LoadingSpinner />
</template>
</Suspense>
</template>
<script>
const AsyncComponent = defineAsyncComponent(() =>
import('./components/HeavyComponent.vue')
)
</script>
4.2 条件懒加载
<script>
export default {
data() {
return {
showChart: false,
ChartComponent: null
}
},
methods: {
async loadChart() {
this.ChartComponent = await import('./components/Chart.vue')
this.showChart = true
}
}
}
</script>
五、第三方库优化
5.1 按需加载示例(以lodash为例)
import debounce from 'lodash/debounce'
5.2 CDN外链(Vue CLI)
module.exports = {
configureWebpack: {
externals: {
vue: 'Vue',
'vue-router': 'VueRouter'
}
}
}
六、进阶优化策略
6.1 Prefetch/Preload
const Home = () => import( './views/Home.vue')
6.2 临界CSS提取
import critical from 'vite-plugin-critical'
export default defineConfig({
plugins: [
critical({
criticalUrl: 'http://localhost:3000',
criticalBase: './dist',
criticalPages: [{ uri: '/', template: 'index' }],
})
]
})
七、性能监控与调优
7.1 Lighthouse审计指标
npx lighthouse http://localhost:3000 --view
7.2 Webpack Bundle分析
npm install --save-dev webpack-bundle-analyzer
module.exports = {
chainWebpack: config => {
config.plugin('BundleAnalyzerPlugin')
.use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
}
}
八、完整示例项目结构
/project-root
/src
/views
Home.vue
Dashboard.vue
/router
index.js
/components
HeavyComponent.vue
main.js
vite.config.js 或 vue.config.js