好的,所以我想我已经想出了如何做到这一点。但首先,这是使用默认 splitChunks 配置构建的样子(注意 FOO.bundle.js 是由动态导入创建的异步包):
Asset Size Chunks Chunk Names
core.bundle.js 605 KiB 0 [emitted] [big] core
coreB.bundle.js 791 KiB 1 [emitted] [big] coreB
coreC.bundle.js 791 KiB 2 [emitted] [big] coreC
a.bundle.js 748 KiB 3 [emitted] [big] a
b.bundle.js 792 KiB 4 [emitted] [big] b
c.bundle.js 674 KiB 5 [emitted] [big] c
FOO.bundle.js 709 bytes 6 [emitted] FOO
runtime.bundle.js 7.49 KiB 7 [emitted] runtime
如果目标是使出现在 core、coreB 和 coreC 中的任何模块不会出现在任何其他包中,则可以通过以下配置完成:
function coreBundleCacheGroups(coreBundles) {
const cacheGroups = {};
const coreChunkNames = Object.keys(coreBundles);
const coreChunkNamesSet = new Set(coreChunkNames);
coreChunkNames.forEach((name) => {
cacheGroups[name] = {
name,
chunks: 'all',
minSize: 0,
minChunks: 1,
reuseExistingChunk: true,
priority: 10000,
enforce: true,
test(module, chunks) {
if (module.depth === 0) {
return false;
}
// Find first core chunk name that matches
const partOfGlobalChunks = chunks.filter(chunk => coreChunkNamesSet.has(chunk.name));
if (!partOfGlobalChunks.length) {
return false;
}
const partOfGlobalChunksSet = new Set(partOfGlobalChunks.map(chunk => chunk.name));
const firstCoreChunkName = coreChunkNames.find(name => partOfGlobalChunksSet.has(name));
return firstCoreChunkName === name;
},
};
});
return cacheGroups;
}
const coreBundles = {
core: './src/bundles/core.js',
coreB: './src/bundles/core-b.js',
coreC: './src/bundles/core-c.js',
};
module.exports = {
mode: 'none',
entry: {
...coreBundles,
a: './src/bundles/a.js',
b: './src/bundles/b.js',
c: './src/bundles/c.js',
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
optimization: {
runtimeChunk: 'single',
splitChunks: {
cacheGroups: {
...coreBundleCacheGroups(coreBundles),
},
},
},
};
产生以下输出:
Asset Size Chunks Chunk Names
core.bundle.js 605 KiB 0 [emitted] [big] core
coreB.bundle.js 188 KiB 1 [emitted] coreB
coreC.bundle.js 1.5 KiB 2 [emitted] coreC
a.bundle.js 76.4 KiB 3 [emitted] a
b.bundle.js 2.28 KiB 4 [emitted] b
c.bundle.js 1.91 KiB 5 [emitted] c
FOO.bundle.js 622 bytes 6 [emitted] FOO
runtime.bundle.js 7.49 KiB 7 [emitted] runtime