Mini-css-extract-plugin: Dynamic import(...) cause duplicate output css

Created on 25 Jul 2018  路  4Comments  路  Source: webpack-contrib/mini-css-extract-plugin

Scenario

index.js:

import("./a");
import("./b");

a.js:
import "./main.css";

b.js:
import "./main.css";

main.css:
body { background: red; }

Output

Building this results in the following outputs:

  • main.js
  • 1.js
  • 1.css
  • 2.js
  • 2.css

As you can see, the original main.css file is now emitted twice in the generated output as 1.css and 2.css.

Is this expected? This seems like unnecessary duplicate css and 2.css could be removed

Most helpful comment

I was able to fix this with: the following webpack config

optimization: {
  // ...
  splitChunks: {
    cacheGroups: {
      styles: {
        test: /\.(css|scss|less)$/,
        enforce: true // force css in new chunks (ignores all other options)
      }
    }
  }
}

All 4 comments

@TheHolyWaffle Use code splitting (i.e. splitChunks.cacheGroups) for this purpose, by default webpack have default group, what do this, please look on documentation and enable this.

@evilebottnawi Do you mind telling me what exactly in the default cacheGroups is causing this effect? The documentation is not very clear on this.

@TheHolyWaffle It is not css/html/etc related issue, you should move same modules to one chunk, you also should do this for js (if you need this), don't disable splitChunks.cacheGroups if you don't know how it is works

I was able to fix this with: the following webpack config

optimization: {
  // ...
  splitChunks: {
    cacheGroups: {
      styles: {
        test: /\.(css|scss|less)$/,
        enforce: true // force css in new chunks (ignores all other options)
      }
    }
  }
}
Was this page helpful?
0 / 5 - 0 ratings