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

image.png
// 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'
在不使用插件的前提下打包結果如下:

image.png
case 1 把多入口entry抽離為common.js
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "common",
filename: "common.js"
})
]
執(zhí)行結果如下:

image.png
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執(zhí)行結果如下:

image.png
//使用commonChunk 配置如下
plugins: [
new webpack.optimize.CommonsChunkPlugin({
children: true,
async: 'children-async',
name: ['main']
})
]
// 執(zhí)行結果如下

image.png
case 3 node_modules所有額三方依賴抽離為vendor.js
//webpack 配置
...
entry : {
main: './src/main.js',
vendor: ['jquery']
}
...
...
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor', // 這里是把入口文件所有公共組件都合并到 vendor模塊當中
filename: '[name].js'
})
...
執(zhí)行結果如果下:

image.png
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']
})
]
....
執(zhí)行結果如下:

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