Vue项目代码分割与懒加载:Webpack与Vite的极致优化实践

Vue项目代码分割与懒加载:Webpack与Vite的极致优化实践

一、首屏加载瓶颈分析

1.1 性能指标

  • FCP (First Contentful Paint)
  • LCP (Largest Contentful Paint)
  • JavaScript执行阻塞时间

1.2 问题根源

  • 单文件打包导致的超大bundle
  • 同步加载未使用的组件
  • 第三方库未合理拆分

二、代码分割核心原理

2.1 动态导入(Dynamic Import)

// 静态导入
// import Home from './views/Home.vue'

// 动态导入
const Home = () => import('./views/Home.vue')

2.2 Webpack分块策略

// webpack.config.js
module.exports = {
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
        }
      }
    }
  }
}

2.3 Vite的ESM原生支持

// vite.config.js
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(/* webpackChunkName: "dashboard" */ './views/Dashboard.vue')
  }
]

3.2 预加载策略

<!-- 使用preload提示 -->
<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 _ from 'lodash'

// 按需引入
import debounce from 'lodash/debounce'

5.2 CDN外链(Vue CLI)

// vue.config.js
module.exports = {
  configureWebpack: {
    externals: {
      vue: 'Vue',
      'vue-router': 'VueRouter'
    }
  }
}

六、进阶优化策略

6.1 Prefetch/Preload

// Webpack魔法注释
const Home = () => import(/* webpackPrefetch: true */ './views/Home.vue')

6.2 临界CSS提取

// vite-plugin-critical
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
// vue.config.js
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

prince_zxill

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值