Skip to content

Vite + Vue3 项目性能优化

一、代码层面优化

1.1 组件优化

  • 合理拆分组件

    • 保持单个组件代码 ≤ 500 行
    • 使用<script setup>语法糖减少样板代码
    • 示例:
      vue
      <script setup>
      const count = ref(0)
      </script>
  • 避免不必要的重新渲染

    • 使用v-once静态标记:
      vue
      <div v-once>{{ staticContent }}</div>
    • 使用v-memo优化列表渲染(Vue 3.2+):
      vue
      <div v-for="item in list" v-memo="[item.id === selected]" :key="item.id">
        {{ item.content }}
      </div>

1.2 响应式优化

  • 合理使用ref/reactive

    js
    // 优先使用 ref 处理原始值
    const count = ref(0)
    
    // 复杂对象使用 reactive
    const state = reactive({ 
      list: [],
      pagination: {}
    })
  • 避免深层响应式

    js
    // 使用 shallowRef/shallowReactive 处理大型数据结构
    const bigData = shallowRef({ ... })

1.3 指令优化

  • v-if 与 v-show 选择

    vue
    <!-- 频繁切换使用 v-show -->
    <div v-show="isVisible">...</div>
    
    <!-- 初始不渲染使用 v-if -->
    <modal v-if="showModal" />
  • 事件委托优化

    vue
    <!-- 使用 .passive 修饰符优化滚动事件 -->
    <div @scroll.passive="handleScroll">

二、构建配置优化

2.1 Vite 基础配置

js
// vite.config.js
export default defineConfig({
  build: {
    target: 'esnext', // 使用最新 ES 特性
    cssCodeSplit: true, // CSS 代码分割
    sourcemap: false // 生产环境关闭 sourcemap
  }
})

2.2 依赖优化

js
// vite.config.js
export default defineConfig({
  optimizeDeps: {
    include: [
      'vue',
      'lodash-es',
      // 添加需要预构建的依赖
    ],
    exclude: ['vue-demi']
  }
})

2.3 Rollup 配置优化

js
build: {
  rollupOptions: {
    output: {
      manualChunks(id) {
        if (id.includes('node_modules')) {
          return 'vendor'
        }
      }
    }
  }
}

三、资源优化

3.1 图片处理

js
// vite.config.js
export default defineConfig({
  plugins: [
    viteImagemin({
      gifsicle: { optimizationLevel: 7 },
      mozjpeg: { quality: 20 },
      pngquant: { quality: [0.8, 0.9] },
      svgo: {
        plugins: [
          { name: 'removeViewBox' },
          { name: 'removeEmptyAttrs', active: false }
        ]
      }
    })
  ]
})

3.2 字体优化

  • 使用font-display: swap
  • 子集化字体文件(使用 pyftsubset 工具)

3.3 预加载关键资源

html
<link rel="preload" href="/critical.css" as="style">
<link rel="preload" href="/main.js" as="script">

四、框架特性优化

4.1 KeepAlive 缓存

vue
<router-view v-slot="{ Component }">
  <keep-alive :max="10">
    <component :is="Component" />
  </keep-alive>
</router-view>

4.2 Suspense 异步组件

vue
<Suspense>
  <template #default>
    <AsyncComponent />
  </template>
  <template #fallback>
    Loading...
  </template>
</Suspense>

五、开发实践优化

5.1 路由懒加载

js
const routes = [
  {
    path: '/dashboard',
    component: () => import('./views/Dashboard.vue')
  }
]

5.2 第三方库按需引入

js
// 错误示例
import _ from 'lodash'

// 正确示例
import debounce from 'lodash-es/debounce'

5.3 Tree Shaking 优化

js
// package.json 配置
{
  "sideEffects": [
    "*.css",
    "*.scss"
  ]
}

六、运行时优化

6.1 虚拟滚动

vue
<VirtualScroller :items="largeList" item-height="50" />

6.2 Web Worker 优化

js
// main.js
const worker = new Worker('./heavy-task.js')

// heavy-task.js
self.onmessage = (e) => {
  const result = heavyCalculation(e.data)
  self.postMessage(result)
}

6.3 性能监测

js
// 使用 Performance API
const measurePerf = () => {
  performance.mark('start')
  // 执行操作
  performance.mark('end')
  performance.measure('操作耗时', 'start', 'end')
}

七、高级优化技巧

7.1 SSR 优化

js
// 使用 vite-plugin-ssr
export default {
  plugins: [
    ssr({
      include: ['**/*.vue', '**/*.js']
    })
  ]
}

7.2 PWA 优化

js
// vite.config.js
import { VitePWA } from 'vite-plugin-pwa'

export default defineConfig({
  plugins: [
    VitePWA({
      registerType: 'autoUpdate',
      workbox: {
        maximumFileSizeToCacheInBytes: 4000000
      }
    })
  ]
})

7.3 CDN 加速

js
// vite.config.js
export default defineConfig({
  build: {
    rollupOptions: {
      external: ['vue', 'axios'],
      output: {
        globals: {
          vue: 'Vue',
          axios: 'axios'
        }
      }
    }
  }
})

最佳实践清单

  1. 使用<script setup>语法糖
  2. 路由组件必须懒加载
  3. 第三方库按需引入
  4. 生产环境关闭 sourcemap
  5. 图片资源必须压缩
  6. 定期执行包分析(使用rollup-plugin-visualizer
  7. 启用 Gzip 压缩(vite-plugin-compression)
  8. 实现组件级缓存策略
  9. 启用 HTTP2 服务器推送
bash
# 包分析命令
npm install rollup-plugin-visualizer --save-dev
js
// vite.config.js
import { visualizer } from 'rollup-plugin-visualizer'

export default defineConfig({
  plugins: [visualizer()]
})

通过持续监控和优化,可使应用性能提升 40%-70%。建议结合 Lighthouse 和 Web Vitals 进行定期检测。