總結一下CommonsChunkPlugin的優(yōu)化過程,一直理解錯了,羞愧難當
api
{
name: string, // or
names: string[],
// 這是 common chunk 的名稱凿歼。已經存在的 chunk 可以通過傳入一個已存在的 chunk 名稱而被選擇擦囊。
// 如果一個字符串數組被傳入塞茅,這相當于插件針對每個 chunk 名被多次調用
// 如果該選項被忽略歼培,同時 `options.async` 或者 `options.children` 被設置震蒋,所有的 chunk 都會被使用茸塞,
// 否則 `options.filename` 會用于作為 chunk 名躲庄。
// When using `options.async` to create common chunks from other async chunks you must specify an entry-point
// chunk name here instead of omitting the `option.name`.
filename: string,
// common chunk 的文件名模板〖嘏埃可以包含與 `output.filename` 相同的占位符噪窘。
// 如果被忽略,原本的文件名不會被修改(通常是 `output.filename` 或者 `output.chunkFilename`)效扫。
// This option is not permitted if you're using `options.async` as well, see below for more details.
minChunks: number|Infinity|function(module, count) -> boolean,
// 在傳入 公共chunk(commons chunk) 之前所需要包含的最少數量的 chunks 倔监。
// 數量必須大于等于2,或者少于等于 chunks的數量
// 傳入 `Infinity` 會馬上生成 公共chunk菌仁,但里面沒有模塊浩习。
// 你可以傳入一個 `function` ,以添加定制的邏輯(默認是 chunk 的數量)
chunks: string[],
// 通過 chunk name 去選擇 chunks 的來源济丘。chunk 必須是 公共chunk 的子模塊谱秽。
// 如果被忽略,所有的摹迷,所有的 入口chunk (entry chunk) 都會被選擇疟赊。
children: boolean,
// 如果設置為 `true`,所有公共 chunk 的子模塊都會被選擇
deepChildren: boolean,
// 如果設置為 `true`峡碉,所有公共 chunk 的后代模塊都會被選擇
async: boolean|string,
// 如果設置為 `true`近哟,一個異步的 公共chunk 會作為 `options.name` 的子模塊,和 `options.chunks` 的兄弟模塊被創(chuàng)建鲫寄。
// 它會與 `options.chunks` 并行被加載吉执。
// Instead of using `option.filename`, it is possible to change the name of the output file by providing
// the desired string here instead of `true`.
minSize: number,
// 在 公共chunk 被創(chuàng)建立之前,所有 公共模塊 (common module) 的最少大小地来。
}
我們希望怎樣打包
- 第三方包(
node_model
)->vendor.js
- 主要入口 (
index.js
) ->app.js
- 路由惰加載 (
codeSplit
)->1.1.js
鼠证、1.2.js
會出現什么問題
- 每次改動代碼,對應
1.1js
等會重新編譯靠抑,但是發(fā)現app.js
也會重新編譯 -
1.1.js
里面有奇怪的東西(node_model
) -
1.1.js
和1.2.js
里面有重復的代碼
怎么解決
- 改動代碼
->
1.1.js
的hash
值改變->
webpack的runtime
代碼中manifest
發(fā)生改變
此時
manifest
存在app.js
量九,把它單獨打包出來:new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', minChunks: Infinity }),
- 有奇怪的東西
->
采用提取render的辦法提取出來
new webpack.optimize.CommonsChunkPlugin({ async: 'async-render', child: true, minChunks: ({ resource } = {}) => ( resource && resource.includes('node_modules') ), }),
child: true
的意思的把所有的子chunk
選中async
在這里的作用是將打包出來的node_model
作為一個獨立的異步子chunk
,否則就會打包進app.js
里面去了
- 有重復代碼:
new webpack.optimize.CommonsChunkPlugin({ async:'async-common', child: true, minChunks: (module, count) => ( count >= 2 ), }),
這樣的結果就是子
chunks
之間的公共代碼也會被作為一個獨立的異步子chunk
被打出來了