How to tell Webpack 5 with splitChunks and MiniCssExtractPlugin to create a separate vendors.css from node_modules using only one entry?

Viewed 151

In my Webpack@5.52.0 project, my goal is to always have index.js, index.css, vendors.js, vendors.css as the result of each build, but with using only one entry (<- important!):

    entry: {
      index: path.resolve(conf.SRC_ROOT, "assets/index.js")
    },

My entry index.js has all the imports like:

require("./index") // <- my scripts
require("./vendors") // <- vendor scripts imports from node_modules
import "./index.scss"; // <- my sytles
import "./vendors.scss"; // <- vendor styles imports from node_modules

So I'm trying to configure code splitting with optimization.splitChunks to let Webpack generate these results/bundles for me:

  • index.js = my scripts
  • index.css = my styles
  • vendors.js = all JS stuff coming from node_modules
  • vendors.css = all CSS stuff coming from node_modules

With the following config (part) Webpack generates only index.js, vendors.js, and index.css which contains all my CSS, so splitting to vendors.css is missing... I've tried a lot of suggestions found on Google but none of them worked.

    optimization: {
      splitChunks: {
        cacheGroups: {
          vendors: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors',
            chunks: 'all',
          }
        }
      },

Excuse me to not pasteing here my huge webpack.config.js but I'm almost certain that the solution hides in a proper splitChunks configuration. FYI: my loaders for styles are: sass-loader -> resolve-url-loader -> postcss-loader -> css-loader -> MiniCssExtractPlugin.loader.

Please note: Currently, I'm using it with 2 entries like this below, and it's working well without any splitChunks config, but I would like to solve the problem I'm asking above.

    // entry: {
    //   vendors: path.resolve(conf.SRC_ROOT, "assets/vendors.js"),
    //   index: {
    //     import: path.resolve(conf.SRC_ROOT, "assets/index.js"),
    //     dependOn: "vendors"
    //   },
    // },

Thank you!

0 Answers
Related