Vue2 老旧项目优化之 splitChunks

学习 · 5 天前
老旧项目打包依赖文件大,需要拆包和分片处理

主要配置代码

const path = require('path')

module.exports = {
  configureWebpack: {
    optimization: {
      splitChunks: {
        chunks: 'all',
        maxSize: 244 * 1024, // 244KB限制
        automaticNameDelimiter: '-', // 强制使用短横线分隔
        hidePathInfo: true, // 隐藏冗余路径信息
        cacheGroups: {
          ui: {
            name: 'ui-lib', // 固定前缀+自动编号
            test: /[\\/]node_modules[\\/](element-ui|vant|antd)/,
            priority: 20,
            chunks: 'all',
            enforce: true,
            reuseExistingChunk: true
          },
          libs: {
            name(module) {
              // 提取npm包名,如 node_modules/echarts → echarts
              const packageName = module.context.match(
                /[\\/]node_modules[\\/](.*?)([\\/]|$)/
              )?.[1]
              return `lib-${packageName.replace('@', '')}` // 处理@scope包
            },
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'all'
          }
        }
      },
      chunkIds: 'deterministic' // 保持hash稳定
    },
    output: {
      filename: '[name].[contenthash:6].js',
      chunkFilename: '[name].[contenthash:6].js' // 统一命名格式
    }
  },
  chainWebpack: config => {
    // 修复Vue CLI默认配置导致的路径泄露
    config.output.set('filename', '[name].[contenthash:6].js')
    config.output.set('chunkFilename', '[name].[contenthash:6].js')
    config.optimization.set('realContentHash', true)
  }
}
Theme Jasmine by Kent Liao | 桂ICP备15008025号-6