Skip to content

Vue CLI + Vue2 项目性能优化

一、构建配置优化

1.1 Webpack 配置调整

javascript
// vue.config.js
module.exports = {
  configureWebpack: {
    optimization: {
      splitChunks: {
        chunks: 'all',
        cacheGroups: {
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors',
            chunks: 'all'
          }
        }
      }
    }
  },
  productionSourceMap: false // 关闭生产环境sourcemap
}

1.2 开启Gzip压缩

bash
npm install compression-webpack-plugin --save-dev
javascript
// vue.config.js
const CompressionPlugin = require('compression-webpack-plugin')

module.exports = {
  configureWebpack: {
    plugins: [
      new CompressionPlugin({
        test: /\.(js|css)$/,
        threshold: 10240, // 对超过10K的数据压缩
        deleteOriginalAssets: false
      })
    ]
  }
}

二、代码层面优化

2.1 组件优化

vue
<!-- 使用函数式组件 -->
<template functional>
  <div class="cell">{{ props.value }}</div>
</template>

<!-- 避免不必要的重新渲染 -->
<template>
  <div v-once>{{ staticContent }}</div>
</template>

2.2 路由懒加载

javascript
// router.js
const Home = () => import(/* webpackChunkName: "home" */ './views/Home.vue')
const About = () => import(/* webpackChunkName: "about" */ './views/About.vue')

2.3 第三方库按需引入

javascript
// 错误示例
import ElementUI from 'element-ui'

// 正确示例
import { Button, Select } from 'element-ui'
Vue.use(Button)
Vue.use(Select)

三、运行时优化

3.1 KeepAlive缓存

vue
<keep-alive :include="cachedViews">
  <router-view></router-view>
</keep-alive>

3.2 优化长列表

vue
<template>
  <virtual-list :size="40" :remain="20" :items="bigData">
    <template v-slot:default="{ item }">
      <div class="list-item">{{ item.content }}</div>
    </template>
  </virtual-list>
</template>

四、资源优化

4.1 图片压缩

javascript
// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.module
      .rule('images')
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({
        mozjpeg: { progressive: true, quality: 65 },
        optipng: { enabled: false },
        pngquant: { quality: [0.65, 0.9], speed: 4 },
        gifsicle: { interlaced: false }
      })
  }
}

4.2 字体优化

css
@font-face {
  font-family: 'MyFont';
  src: url('myfont.woff2') format('woff2'),
       url('myfont.woff') format('woff');
  font-display: swap;
}

五、高级优化技巧

5.1 DLL加速构建

javascript
// webpack.dll.config.js
const path = require('path')
const webpack = require('webpack')

module.exports = {
  entry: {
    vendor: ['vue', 'vue-router', 'vuex']
  },
  output: {
    path: path.join(__dirname, 'dll'),
    filename: '[name].dll.js',
    library: '[name]_library'
  },
  plugins: [
    new webpack.DllPlugin({
      path: path.join(__dirname, 'dll', '[name]-manifest.json'),
      name: '[name]_library'
    })
  ]
}

5.2 CDN加速

javascript
// vue.config.js
module.exports = {
  configureWebpack: {
    externals: {
      vue: 'Vue',
      'vue-router': 'VueRouter',
      vuex: 'Vuex'
    }
  }
}
html
<!-- public/index.html -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-router@3.5.1/dist/vue-router.min.js"></script>

六、性能监控

6.1 Webpack包分析

bash
npm install webpack-bundle-analyzer --save-dev
javascript
// vue.config.js
module.exports = {
  chainWebpack: config => {
    config
      .plugin('webpack-bundle-analyzer')
      .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
  }
}

6.2 Lighthouse检测

bash
npm install -g lighthouse
lighthouse http://localhost:8080 --view

最佳实践清单

  1. 生产环境禁用devtools
javascript
Vue.config.devtools = process.env.NODE_ENV !== 'production'
  1. 使用ES6语法
javascript
// 使用箭头函数减少this绑定
methods: {
  handleClick: () => {
    // ...
  }
}
  1. 优化事件监听
vue
<template>
  <div @scroll.passive="handleScroll">
</template>
  1. 合理使用computed属性
javascript
computed: {
  filteredList() {
    return this.list.filter(item => item.active)
  }
}
  1. 及时销毁全局事件
javascript
beforeDestroy() {
  window.removeEventListener('resize', this.handleResize)
}
  1. 优化Vuex使用
javascript
// 使用mapState替代直接访问store
computed: {
  ...mapState(['userInfo'])
}
  1. 启用HTTP缓存
nginx
# nginx配置示例
location /static {
  expires 1y;
  add_header Cache-Control "public";
}
  1. 使用最新稳定版本依赖
bash
npm outdated # 定期检查过期依赖

通过上述优化手段,通常可将构建体积减少30%-50%,首屏加载时间优化40%以上。建议结合性能监控工具持续优化。