首页 > 解决方案 > Webpack 4 splitChunks 生成多个 css

问题描述

我正在尝试使用 webpack 4 min-css-extract-plugin 和 splitChunks 插件生成多个 css。

这是我的 webpack 配置。

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");

module.exports = [{
  entry: './index.js',
  output: {
    filename: '[name].js',
    path: path.resolve(path.join(__dirname, "./dist")),
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: false,
        commons: {
          name: 'commons',
          test: /.styl$/,
          chunks: 'all',
          enforce: true,
          minChunks: 1,
        },
        englishStyle: {
          name: 'styles_en',
          test: (c) => {
            return c.type.match(/mini-css-extract-plugin/) && c._identifier.indexOf('_ar') === -1;
          },
          chunks: 'all',
          priority: 1,
          enforce: true,
        },
        arabicStyles: {
          name: 'styles_ar',
          test: (c) => {
            return c.type.match(/mini-css-extract-plugin/) && c._identifier.indexOf('_ar') !== -1;
          },
          priority: 1,
          chunks: 'all',
          enforce: true,
        }
      }
    }
  },
  module: {
    rules: [
      {
        test: /\.styl$/,
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          "stylus-loader"
        ],
      },
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[name].css"
    })
  ]
}]

这是我的css文件结构。

common.styl
  ...

style.styl 
  @import common.styl
  ...

style_ar.styl
  @import common.styl
  ...

index.js
 import styles from style.styl
 import styles from style_ar.styl

上面的配置只生成了styles_ar.css和style.css两个文件。在两个文件中都有共同的内容。

如何为公共文件生成单独的文件?

如果我优先考虑commons cacheGroup 只会生成一个文件commons.styl。

标签: csswebpackwebpack-4webpack-splitchunks

解决方案


这是一种“否定”的答案,但如果你指出我错过了什么 - 我会放弃它。

1) css 虽然 MiniCssExtractPlugin 是一种人们用来不创建 gulp 文件来生成 css 文件的技巧 - 他们只想将所有内容保存在一个地方(并编写更少的代码)。为什么这是可能的 - 一切都很好 - 但不要忘记这仍然是一个技巧。

这是你的动力吗?或者在现实生活中,您需要将高度特定的 webpack 插件包含到 css 生产过程中?我不是在谈论 autoprefixer - 你也可以使用 gulp 的 post-css。但是真正特定于 webpack 的东西?可能是一些 webpack 运行时特性?

2) 这不是一个好主意来“强迫”一个技巧不仅仅是技巧。

注意:当您想要创建“一个用于 css 和 js 的混合包”时,我们不涵盖这种情况——这意味着css-loader不使用MiniCssExtractPlugin它——这将是一个完全不同的故事。

所以答案是:直接用stylus生成你想要的chunked css。

或尝试“更重的技巧”:https ://github.com/faceyspacey/extract-css-chunks-webpack-plugin


推荐阅读