Search code examples
javascriptcsswebpackbundlecreate-react-app

How to change the CSS bundle name using a Webpack config override in CRA?


I currently have a config-overrides.js file that I use to change the bundle names that Create React App generates for JS files. I'd love to be able to apply similar logic to my CSS bundles.

Here are the contents of the config overrides files:

module.exports = function override(config, webpackEnv) {
  const isEnvDevelopment = webpackEnv === 'development';
  const isEnvProduction = webpackEnv === 'production';

  config.output.filename = isEnvProduction
    ? 'static/js/[name].js?nocache=[contenthash:8]'
    : isEnvDevelopment && 'static/js/bundle.js';
  config.output.chunkFilename = isEnvProduction
    ? 'static/js/[name].chunk.js?nocache=[contenthash:8]'
    : isEnvDevelopment && 'static/js/[name].chunk.js';

  return config
}

How can I achieve the same results but for CSS bundles/chunks?

EDIT: I've noticed I skipped the fact that I'm using react-app-rewired for the config overrides.


Solution

  • I dont think so, specially at this current time. CRA has a hack that can break the wholething. CRA got left behind, postcss current version is 8 and some packages used by CRA use version 7 of postcss and v8 came with break changes. Even if you were able to do that, you wont be able to fixed the rest w/out ejecting.

    BUT, there is a huge but, CRA uses this webpack on their plugins section.

    of the problems.new MiniCssExtractPlugin({
                // Options similar to the same options in webpackOptions.output
                // both options are optional
                filename: "static/css/[name].[contenthash:8].css",
                chunkFilename: "static/css/[name].[contenthash:8].chunk.css",
            }), 
    

    and also they have a webpack loader

        // "file" loader makes sure those assets get served by WebpackDevServer.
                        // When you `import` an asset, you get its (virtual) filename.
                        // In production, they would get copied to the `build` folder.
                        // This loader doesn't use a "test" so it will catch all modules
                        // that fall through the other loaders.
                        {
                            loader: require.resolve("file-loader"),
                            // Exclude `js` files to keep "css" loader working as it injects
                            // its runtime that would otherwise be processed through "file" loader.
                            // Also exclude `html` and `json` extensions so they get processed
                            // by webpacks internal loaders.
                            exclude: [ /\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/ ],
                            options: {
                                name: "static/media/[name].[hash:8].[ext]",
                            },
                        },