Search code examples
vue.jswebpackvuejs3webpack-5

Extract css per entry point in webpack


Anyway to tell webpack in a project with multiple entries to include only respective css for each entry?

Seems like it extracts all css across all entries, puts them under vendor.css and includes that css into all of the entries. And I can't figure out how to tell it to separate the css per entry.

It's a Vue3 project, but the solution should be webpack specific.

Anyway, my vue.config.js goes something like this:

module.exports = {
    ...
    pages:{
        entry1:{
            entry:"./src/entry/entry1.js",
            template:"public/entry1.html"
        },
        entry2:{
            entry:"./src/entry/entry2.js",
            template:"public/entry2.html"
        }
    },
    ...

    configureWebpack:{
        ...
    }
}

entry1.js:

import css1.css
...

entry2.js:

import css2.css
...

Now I need to build entry1.html with only styles from css1.css included and entry2.html with only styles from css2.css included.

Instead webpack combines all styles from both css1.css and css2.css into a single file and includes that resulting file into the both htmls.

I was trying to play around with MiniCssExtractPlugin configs and chunk naming but no luck so far.


Solution

  • Ok, the solution was as simple as setting optimization.splitChunks.minChunks = 2 (since I have two entries):

    configureWebpack: {
        optimization: {
            splitChunks: {
                ...
                minChunks: 2, // <- this was the fix. Indicates that modules must be imported at least twice before merging them into a common chunk
        }
    }
    

    split-chunks-plugin doc reference