总结一下CommonsChunkPlugin的优化过程,一直理解错了,羞愧难当
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` 的兄弟模块被创建。
// 它会与 `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 被创建立之前,所有 公共模块 (common module) 的最少大小。
}
我们希望怎样打包
- 第三方包(
node_model
)->vendor.js
- 主要入口 (
index.js
) ->app.js
- 路由惰加载 (
codeSplit
)->1.1.js
、1.2.js
会出现什么问题
- 每次改动代码,对应
1.1js
等会重新编译,但是发现app.js
也会重新编译 -
1.1.js
里面有奇怪的东西(node_model
) -
1.1.js
和1.2.js
里面有重复的代码
怎么解决
- 改动代码
->
1.1.js
的hash
值改变->
webpack的runtime
代码中manifest
发生改变
此时
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
被打出来了
网友评论