Combine all css files into one via webpack config-override

Viewed 719

I'm doing a refactor in a big react application to serve as a microfrontend application. And i need to generate just one single css file in the root folder, the project has styled-components, css and scss files. It was built with create-react-app and has config-overrides. How can i do that?

    config => {
      config.entry = "./src/app-legacy.js";
      config.output = {
        ...config.output,
        filename: "app-legacy.js",
        libraryTarget: "system",
        publicPath: projectURI
      };
      config.externals = ["single-spa", "react", "react-dom"];
      delete config.optimization;

      config.plugins.push(
        new MiniCssExtractPlugin({ filename: "app-legacy.css" })
      );
      config.module.rules.push({
        test: /\.(sa|sc|c)ss$/,
        use: ["css-loader", "sass-loader", MiniCssExtractPlugin.loader]
      });
      config.plugins = config.plugins.filter(
        plugin => plugin.constructor.name !== "HtmlWebpackPlugin"
      );
      return config;
    }

I'm currently trying to do this with MiniCssExtractPlugin but i can't make it work

1 Answers

You need to add "chunkFilename" option in your MiniCssExtractPlugin object like this:

config.plugins.push(
    new MiniCssExtractPlugin({ 
          filename: "app-legacy.css",
          chunkFilename: '[name].[hash].css', })
  );

and also rearrange your rules for css/scss file to:

 config.module.rules.push({
    test: /\.(sa|sc|c)ss$/,
    use: [MiniCssExtractPlugin.loader,'css-loader', 'sass-loader',]
  });

so, now the webpack will parse the css/scss/sass file with sass-loader first and then with the css-loader and then finally with MiniCssExtractPlugin.loader to make a css chunk.

Related