首页 > 解决方案 > Webpack MiniCssExtractPlugin:如何为每个条目创建 css 文件?

问题描述

我在 webpack 配置中有两个条目:

module.exports = {
  entry: {
    mobile: './src/mobile/index.js',
    desktop: './src/desktop/index.js',
  },
};

我想获得下一个捆绑结构:

dist
├── mobile
│   ├── index.js
│   └── index.css
└── desktop
    ├── index.js
    └── index.css

我尝试根据这部分文档配置 webpack: https ://webpack.js.org/plugins/mini-css-extract-plugin/#extracting-css-based-on-entry

但是在我的 dist 文件夹中,我得到了下一个结构:

dist
├── mobile
│   └── index.js
├── desktop
│   └── index.js  
└── styles_mobile
    └── index.css

也没有“styles_desktop”文件夹。

我的配置看起来像:

module.exports = {
  entry: {
    mobile: './src/mobile/index.js',
    desktop: './src/desktop/index.js',
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        mobileStyles: {
          name: "styles_mobile",
          test: (m, c, entry = "mobile") =>
            m.constructor.name === "CssModule" &&
            recursiveIssuer(m, c) === entry,
          chunks: "all",
          enforce: true,
        },
        desktopStyles: {
          name: "styles_desktop",
          test: (m, c, entry = "desktop") =>
            m.constructor.name === "CssModule" &&
            recursiveIssuer(m, c) === entry,
          chunks: "all",
          enforce: true,
        },
      },
    },
  },
  // ...
};

当我将“styles_mobile”更改为“mobile”并将“styles_desktop”更改为“desktop”时,出现错误:

ERROR in SplitChunksPlugin
  Cache group "mobile" conflicts with existing chunk.
  Both have the same name "mobile" and existing chunk is not a parent of the selected modules.
  Use a different name for the cache group or make sure that the existing chunk is a parent (e. g. via dependsOn).
  HINT: You can omit "name" to automatically create a name.
  BREAKING CHANGE: webpack < 5 used to allow to use an entrypoint as splitChunk. This is no longer allowed when the entrypoint is not a parent of the selected modules.
  Remove this entrypoint and add modules to cache group's 'test' instead. If you need modules to be evaluated on startup, add them to the existing entrypoints (make them arrays). See migration guide of more info.

我做错了什么?

标签: csswebpackstylesbundlemini-css-extract-plugin

解决方案


推荐阅读