【webpack】中splitChunk的使用方法

适合在多入口打包中使用

const path = require('path')
const webpack = require('webpack')

module.exports = {
  entry: {
    a: './src/a.js',
    b: './src/b.js'
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].bundle.js',
  },
  optimization: {
    // async 异步(import()语法) initial(同步import xxx from 'xxx') all(所有)
    splitChunks: {
      chunks: 'initial'
    }
  }
}

a入口和b入口都引入了jquery,打包时也分别打包到了各自的模块里面,那么我们可以把相同的模块提取出来

【webpack】中splitChunk的使用方法

还有一些参数,看到那个vendors单词没,默认在这里设置的

  optimization: {
    splitChunks: {
      chunks: 'initial',
      cacheGroups: {
        vendors: {
          test: /[\/]node_modules[\/]/,
          priority: -10
        }
      }
    }
  },

尝试改成其他名字

  optimization: {
    splitChunks: {
      chunks: 'initial',
      cacheGroups: {
        common: {
          test: /[\/]node_modules[\/]/,
          priority: -10
        }
      }
    }
  },

出来的是这样的

【webpack】中splitChunk的使用方法

可以定义很多个规则

比如我们想react和react-dom打一个包,vue和vuex打一个包

  optimization: {
    splitChunks: {
      chunks: 'initial',
      cacheGroups: {
        vue: {
          test: /[\/]node_modules[\/](react|react-dom)/,
          priority: -1
        },
        react: {
          test: /[\/]node_modules[\/](vue|vuex)/,
          priority: -2
        }
      }
    }
  },

【webpack】中splitChunk的使用方法

默认引入的node_modules提取的的公共文件叫做vendors命名

可以自定义处理不同模块,要写priority,默认是-10,按照数字大的处理。