Bunding modules into chunk groups with webpack cacheGroups

721 views Asked by At

In our application, each module is dynamically downloaded based on a condition, and we want to control which modules are bundled together (using webpack).

So for example assume we have the following code:

if (condition1) m1 = import('./m1')
if (condition2) m2 = import('./m2')
if (condition3) m3 = import('./m3')
if (condition4) m4 = import('./m4')

(each file is also statically importing other files)

since we know that condition1 and condition2 are both true together (same for 3 and 4), we want to bundle m1 and m2 (and all the files that they import) to a chunk called m1-m2, and m3 and m4 (and all the files that they import) to a chunk called m3-m4.

to do that we are using webpack cachegroups (webpack.config):

splitChunks: { 
    chunks: 'all',
    cacheGroups: {
        'm1-m2': {
            test: (module, { chunkGraph }) => {
                const chunks = chunkGraph.getModuleChunks(module)
                return chunks.some(({ name }) => ['m1','m2'].includes(name))
            }
        },
        'm3-m4': {
            test: (module, { chunkGraph }) => {
                const chunks = chunkGraph.getModuleChunks(module)
                return chunks.some(({ name }) => ['m3','m4'].includes(name))
            }
        }
    }
}

This works great when there are no shared files between the 2 groups, but when there are shared files between the modules, webpack will bundle the shared file only in one of the groups, and create a dependency between the second group to the first group.

For example, if m1.js and m3.js are both using some file a.js and webpack decided to bundle it in m1-m2, then when m3.js is dynamically loaded, both groups will be loaded because m3.js needs a.js. and it is located in m1-m2

This is obviously not the desired behavior, since we want each chunk to bundle the entire code of the modules (including the shared code - since we know that m1 and m2 are not loaded together with m3 and m4)

we want webpack to bundle a.js in both m1-m2 and m3-m4, is it possible using cacheGroups?

0

There are 0 answers