Search code examples
webpack-2postcss

Nicer class names in PostCSS


I'm building my app using Webpack 2. I'm using PostCSS 2 for CSS modules. Here is my CSS importing configuration for Webpack:

  {
    test: /\.css$/,
    exclude: /(node_modules)/,
    use: [
      'style-loader',
      {
        loader: 'css-loader',
        options: {
          modules: true,
          importLoaders: 1,
        },
      },
      {
        loader: 'postcss-loader',
        options: {
          plugins: loader => [
            require("postcss-import")({
              path: './js',
              addDependencyTo: webpack,
            }),
            require('postcss-cssnext')(),
          ],
        },
      },
    ],
  },

Now, the problem is, that this generates really ugly class names. Example using React:

import React, {Component} from 'react';
import styles from './Element.css';

export default class Element extends Component{
  render(){
    return (
      <div className={styles.myElement}>This is an example.</div>
    );
  }
}

Renders into:

<div class="_1DHVkmCxFFQMFYac-L_MIg">This is an example.</div>

Now, this is fine in production, but in development, something like class="myElement--_1DHVkmCxFFQMFYac-L_MIg" would be a lot nicer. I found a GitHub issue discussing this, but as I'm new to Webpack, I couldn't figure out how to implement their suggestion. Whatever I tried resulted in an error, where Webpack couldn't resolve the module.

I tried adding localIdentName: '[local]--[hash:base64:5]' to postcss-loader options, but that did nothing.

So, how do I retain the original class name in the generated class name?


Solution

  • Adding this line to the css-loader resolved it:

    localIdentName: debug ? '[name]_[local]___[hash:base64:10]' : undefined,