philw
philw

Reputation: 687

Webpack-4 MiniCssExtractPlugin splitChunks

I'm trying to get the Webpack-4 splitChunks optimization to do this:

  1. Put all JS&CSS not in any entry point but used more than once into common files (CSS & JS).
  2. Combine all CSS produced by the MiniCssExtractPlugin from Vue components into the same common CSS file.

I have this working (below), but the effect of the second "extractedStuff" rule is to put all the entry point code into the shared chunk also, which is what I'm trying to prevent with that "test". The "entry point" files are just webpack stubs, and everything is in the common file even if it's used only once. It works, but it's not elegant.

Does anyone know how to exclude the entry points from that second rule, or is there a better way to do this overall?

Does anyone know where the definition of those "module,chunks" objects are, as perhaps I can make that test better some how.

splitChunks: {

    cacheGroups: {     // Idea from github.com/webpack/webpack/issues/7230
        mainJS: {
            test: /\.js$/,
            name: "commons",
            chunks: "all",
            minChunks: 2,   // Makes it leave entry point JS alone.
            minSize: 0,
            priority: 20,
            enforce: true
        },
        extractedStuff: {
            test: (module, chunks) => module.depth > 0, 
            name: "commons", // Append to same file as previous rule.
            chunks: "all",
            minChunks: 1,   // ..or single-use CSS is not bundled.
            minSize: 0,
            priority: 10,
            enforce: true
        }
}

},

Upvotes: 1

Views: 2183

Answers (1)

philw
philw

Reputation: 687

I'm fumbling with this, but here's how I fixed my problem...

The problem with the above is that the extractedStuff entry messes up the bundling because it necessarily has minChunks set to 1. That entry has to be removed: I can't combine the extracted CSS like that.

I experimented with building a plugin to combine the CSS myself, but the problem with that is that it leaves it un-de-duplicated: you get multiple copies of CSS that way.

Instead, this seems to work perfectly, taken from the Mini-Css-Extract-Plugin advice.

      cacheGroups: {
            mainJS: {
                test: /\.js$/,
                name: "commons",
                chunks: "all",
                minChunks: 2,
                minSize: 0,
                priority: 20,
                enforce: true
            },
            extractedCSS: {
                test: (module, chunks) => module.constructor.name === 'CssModule',
                name: "commons",
                chunks: "all",
                enforce: true
            }
        }

Upvotes: 1

Related Questions