# webpack 性能优化

# 1. 拆分 bundle

示例:(基于 vue-cli)

const { defineConfig } = require('@vue/cli-service');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

const {
  NODE_ENV,
  ANALYZE,
} = process.env;

const IS_DEV = NODE_ENV === 'development';
const IS_ANALYZE = ANALYZE === 'YES';

module.exports = defineConfig({

  configureWebpack: {
    devtool: IS_DEV ? 'cheap-module-source-map' : false,

    plugins: [
      IS_ANALYZE ? new BundleAnalyzerPlugin() : null,
    ].filter(Boolean),

    optimization: {
      splitChunks: {
        chunks: 'all',
        cacheGroups: {
          vue: {
            priority: 40,
            test: /[\\/]node_modules[\\/]@?vue(.*)?[\\/]/,
            name: 'vue',
          },
          'ant-design-vue': {
            priority: 30,
            test: /[\\/]node_modules[\\/]@?ant-design-vue[\\/]/,
            name: 'ant-design-vue',
          },
          'spread-sheets-designer': {
            priority: 29,
            test: /[\\/]node_modules[\\/]@grapecity[\\/]spread-sheets-designer[\\/]/,
            name: 'spread-sheets-designer',
          },
          'spread-sheets': {
            priority: 28,
            test: /[\\/]node_modules[\\/]@grapecity[\\/]spread-sheets[\\/]/,
            name: 'spread-sheets',
          },
          'spread-sheets-charts': {
            priority: 27,
            test: /[\\/]node_modules[\\/]@grapecity[\\/]spread-sheets-charts[\\/]/,
            name: 'spread-sheets-charts',
          },
          'spread-sheets-pdf': {
            priority: 26,
            test: /[\\/]node_modules[\\/]@grapecity[\\/]spread-sheets-pdf[\\/]/,
            name: 'spread-sheets-pdf',
          },
          'spread-excelio': {
            priority: 25,
            test: /[\\/]node_modules[\\/]@grapecity[\\/]spread-excelio[\\/]/,
            name: 'spread-excelio',
          },
          'spread-others': {
            priority: 20,
            test: /[\\/]node_modules[\\/]@grapecity[\\/]/,
            name: 'spread-others',
          },
          others: {
            priority: 10,
            test: /[\\/]node_modules[\\/]/,
            name: 'others',
          },
        },
      },
      runtimeChunk: {
        name: (entrypoint) => `runtime~${entrypoint.name}.js`,
      },
    },
  },
});

# 2. 预加载异步模块

routes.js:

const routes = [
  {
    path: '/online-excel',
    name: 'OnlineExcel',
    component: () => import(/* webpackPrefetch: true */ '@/views/online-excel/OnlineExcel.vue'),
    meta: { title: 'OnlineExcel' },
  },
]

# 3. 参考

本章目录