迁移到webpack4:从webpack.optimize.CommonsChunkPlugin到config.optimization.splitChunk,以及有个搜出来的中文解决办法是错的

今天在对着webpack中文指南一点点敲demo,在代码分离这一节遇到了一个报错:

webpack4 Error: webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead

哦,原来是原来的插件不能用了,这个中文指南,标的是webpack4.7.0,结果这块都没更新啊。。。于是必应搜了一下,第一个出来的是这个

webpack4 Error: webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead 的解决方法

照着在webpack.config.js改了一下代码:

  module.exports = {
    plugins: [
-     new webpack.optimize.CommonsChunkPlugin({
-       name: 'common' // 指定公共 bundle 的名称。
-     })
    ],

+   optimization: {
+     splitChunks: {
+       name: 'common'
+     }
+   },

倒是不报错了,但仔细检查了一下,发现结果是:

//app.bundle.js 和 another.bundle.js 是共享 lodash模块的
                Asset       Size  Chunks             Chunk Names
    another.bundle.js   70.1 KiB       0  [emitted]  another
        app.bundle.js   70.2 KiB       1  [emitted]  app
another.bundle.js.map    668 KiB       0  [emitted]  another
    app.bundle.js.map    668 KiB       1  [emitted]  app
           index.html  253 bytes          [emitted]  

app.bundle.js 和 another.bundle.js 的大小都在70kib左右(1kib = 1,024Byte),相差无几且都大得不对劲,而且common.js根本没有生出来啊。。。这绝壁是有问题吧!!!

返回去老老实实看官方文档吧。。。

果然,是要这么配滴:

//optimization与entry/plugins同级
optimization: {
        splitChunks: {
            cacheGroups: {
                commons: {
                    name: "commons",
                    chunks: "initial",
                    minChunks: 2
                }
            }
        }
    },

稍微解释一下含义

  • cacheGroups is an object where keys are the cache group names. All options from the ones listed above are possible: chunks, minSize, minChunks, maxAsyncRequests, maxInitialRequests, name. 可以自己设置一组一组的cache group来配对应的共享模块
  • commons里面的name就是生成的共享模块bundle的名字
  • With the chunks option the selected chunks can be configured.
    chunks 有三个可选值,”initial”, “async” 和 “all”. 分别对应优化时只选择初始的chunks,所需要的chunks 还是所有chunks 。
  • minChunks 是split前,有共享模块的chunks的最小数目 ,默认值是1, 但我看示例里的代码在default里把它重写成2了,从常理上讲,minChunks = 2 应该是一个比较合理的选择吧。

出来的结果是:

                Asset       Size  Chunks             Chunk Names
    commons.bundle.js   69.5 KiB       0  [emitted]  commons
    another.bundle.js   1.21 KiB       1  [emitted]  another
        app.bundle.js   1.26 KiB       2  [emitted]  app
commons.bundle.js.map    664 KiB       0  [emitted]  commons
another.bundle.js.map    6.9 KiB       1  [emitted]  another
    app.bundle.js.map   7.31 KiB       2  [emitted]  app
           index.html  317 bytes          [emitted]  

很明显这才是对的嘛~

对了,那个回答在某个叫skip的社区上,已经有4964浏览量了。。。。不得不觉得有点误人子弟啊。。。

猜你喜欢

转载自blog.csdn.net/github_36487770/article/details/80228147