#明確概念
- entry的每一個入口檔案都叫chunk (entry chunk)
- 每個入口檔案非同步載入也叫chunk(children chunk)
- 通過commonChunkPlugin 抽離出來的也叫chunk(common chunk)
#使用場景
- 多入口檔案,需要抽出公告部分的時候。
- 單入口檔案,但是因為路由非同步載入對多個子chunk, 抽離子每個children公共的部分。
- 把第三方依賴,理由node_modules下所有依賴抽離為單獨的部分。
- 混合使用,既需要抽離第三方依賴,又需要抽離公共部分。
#實現部分 專案結構

// a.js
import { common1 } from './common'
import $ from 'jquery';
console.log(common1, 'a')
//b.js
import { common1 } from './common'
import $ from 'jquery';
console.log(common1, 'b')
//common.js
export const common1 = 'common1'
export const common2 = 'common2'
複製程式碼
在不使用外掛的前提下打包結果如下:

case 1 把多入口entry抽離為common.js
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "common",
filename: "common.js"
})
]
複製程式碼
執行結果如下:

case 2 從children chunk抽離 common.js
// 單入口檔案 main.js
const component1 = function(resolve) {
return require(['./a'], resolve)
}
const component2 = function(resolve) {
return require(['./b'], resolve)
}
console.log(component1, component2, $, 'a')
複製程式碼
不使用commonChunk執行結果如下:

//使用commonChunk 配置如下
plugins: [
new webpack.optimize.CommonsChunkPlugin({
children: true,
async: 'children-async',
name: ['main']
})
]
複製程式碼
// 執行結果如下

case 3 node_modules所有額三方依賴抽離為vendor.js
//webpack 配置
...
entry : {
main: './src/main.js',
vendor: ['jquery']
}
...
...
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor', // 這裡是把入口檔案所有公共元件都合併到 vendor模組當中
filename: '[name].js'
})
...
複製程式碼
執行結果如果下:

case 4 case 2和case 3混合使用 vendor.js是三方依賴提取,0.js是children公共部分提取
....
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: '[name].js'
}),
new webpack.optimize.CommonsChunkPlugin({
children: true,
async: 'children-async',
name: ['main']
})
]
....
複製程式碼
執行結果如下:

#注意的幾點
- name: 如果entry和CommonsChunkPlugin的 name 都有vendor 是把抽離的公共部分合併到vendor這個入口檔案中。 如果 entry中沒有vendor, 是把入口檔案抽離出來放到 vendor 中。
- minChunks:既可以是數字,也可以是函式,還可以是Infinity。
數字:模組被多少個chunk公共引用才被抽取出來成為commons chunk
函式:接受 (module, count) 兩個引數,返回一個布林值,你可以在函式內進行你規定好的邏輯來決定某個模組是否提取 成為commons chunk
Infinity:只有當入口檔案(entry chunks) >= 3 才生效,用來在第三方庫中分離自定義的公共模組 - commonChunk 之後的common.js 還可以繼續被抽離,只要重新new CommonsChunkPlugin中name:配置就好就可以實現
- 以上方法只使用與 webpack 4 以下版本