首页 > 技术文章 > 使用webpack.optimize.CommonsChunkPlugin提供公共代码

qiufang 2018-03-12 19:29 原文

在webpack4里使用webpack.optimize.CommonsChunkPlugin时,报错,webpack4删除了常用的 CommonsChunkPlugin ,提示我们用config.optimization.splitChunks这个,

但是改成这个之后还是报错“TypeError: Cannot read property 'splitChunks' of undefined”

后面搜索找到了个解决办法:

config.entry = {
  app:path.join(__dirname,'src/index.js'),
  vendor:['vue']
}

config.optimization = {

splitChunks: {

  cacheGroups: {// 这里开始设置缓存的 chunks

    commons: {

      chunks: 'initial',// 必须三选一: "initial" | "all"(默认就是all) | "async"

      minChunks: 2,// 最小 chunk ,默认1

      maxInitialRequests: 5,// 最大初始化请求书,默认1

      minSize: 0 // 最小尺寸,默认0

    },

    vendor: {// key 为entry中定义的 入口名称

      test: /node_modules/,// 正则规则验证,如果符合就提取 chunk

      chunks: 'initial',

      name: 'vendor',// 要缓存的 分隔出来的 chunk 名称 

      priority: 10,// 缓存组优先级

      enforce: true

    }

  }

},

runtimeChunk: true

}

 

具体webpack4版本特性,可以翻阅以下文章:

https://github.com/webpack/webpack/releases,

https://zhuanlan.zhihu.com/p/34028750,

http://ju.outofmemory.cn/entry/343762

推荐阅读