遷移到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瀏覽量了。。。。不得不覺得有點誤人子弟啊。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章