2

I am building a React application through Webpack 2, generating CSS through SASS-loader and CSS-loader. Here is my Webpack 2 configuration:

loaders: [
        {
            test: /\.(css|scss)$/,
            use: ExtractTextPlugin.extract({
                fallback: 'style-loader',
                use: [
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true,
                            importLoader: 1,
                            camelCase: true,
                            localIdentName: '[local]',
                            minimize: {
                                safe: true,
                            },
                        }
                    },
                    {
                        loader: 'sass-loader'
                    }
                ],
            })
        },
        [...]
     ]

I am writing the resulting CSS to file, while allowing my React application to get the resulting class names in a Javascript object to assign to various HTML elements.

One quirk I've seen is that empty classes (class selectors containing no actual styles) are not being kept, and are discarded from the class list on generation. I have read that CSS-loader uses CSSNano, whose configuration by default removes unused/empty classes through minification.

As per CSS-Loader's documentation, you can set CSSNano options through the minimize option. That is why I have set safe as true, as per CSSNano's options documentation.

Unfortunately, empty/unused classes are still not being kept. I am wondering if I'm properly passing the CSSNano option through.

Any thoughts on why empty classes aren't persisting?

Prusprus
  • 7,987
  • 9
  • 42
  • 57
  • Why would you want to do that? it goes against the whole idea of using css modules, isn't it? – vma Mar 19 '17 at 12:16
  • 1
    Yes, as its default configuration. We are trying to integrate this into our React environment, though sometimes we are pushing classes onto HTML elements for external components to be able to gain access to those elements through those classes, even if its related SCSS file may not have styles attributed to it (throwing the cleanup on itself). So you're right in that in most cases, empty class cleanup is preferred, in our case (for the time being at least), we were looking to disable this cleanup. – Prusprus Mar 21 '17 at 17:15
  • We have had similar situation, where we want an element to have a class name retained so that a global css could style it (for example icon fonts). We found classnames package (https://github.com/JedWatson/classnames) quite useful. If we define apply classnames cx("local_styles", "icon_global") and we do not have icon_global defined in the local css, the classname package retains the icon_global class as is - only local_styles get uniquified by the css modules – vma Mar 22 '17 at 20:42

0 Answers0