Search code examples
cssreactjscss-modulesreact-css-modules

Normal CSS with CSS Modules


I was previously using bootstrap css import fine previously.

However I'm trying to use CSS module so I added a few lines.

  {
        test: /\.css$/,
        use:  [
          'style-loader',
          { 
            loader: 'css-loader', 
            options: { 
              importLoaders: 1, 
              modules: true, //<- Added to enable css module
              localIdentName: '[name]__[local]___[hash:base64:5]' //<-Added to enable css module
            }
          },
          'postcss-loader'
        ]
      },

Now I'm able to use the following sample codes

  import styles from 'styles.css'

and use it in the code like this

  <div className={styles.container}></div>

and it becomes like this in browser

  <div class="styles__container___3dfEE"></div>

I have the following in my index.js

  import 'bootstrap/dist/css/bootstrap.min.css';

Now, all my classes from bootstrap.min.css are no longer working.

How can i enable both css modules as well as continue to use bootstrap css normally?

I'm currently using a "dirty" way to do it, by saving my custom styles as styles.sss instead and added the following codes in webpack config. Not sure whether it will have any issues.

{
    test: /\.css$/,
    use:  [
      'style-loader',
      { 
        loader: 'css-loader', 
        options: { 
          importLoaders: 1
        }
      },
      'postcss-loader'
    ]
  },
    {
    test: /\.sss$/,
    use:  [
      'style-loader',
      { 
        loader: 'css-loader', 
        options: { 
          importLoaders: 1, 
          modules: true,
          localIdentName: '[name]__[local]___[hash:base64:5]'
        }
      },
      'postcss-loader'
    ]
  }

Solution

  • you need to import bootstrap's css without going through your original webpack config:

    import "!style-loader!css-loader!bootstrap/dist/css/bootstrap.min.css";
    

    this will activate the style-loader and css loader but without the modules: true option