Skip to content Skip to sidebar Skip to footer

CSS Modules Not Working For React Version 16.6.0

I was trying to use CSS Modules in React. Here my code of App.js import React from 'react'; import styles from './index.css' const App = () => { const REACT_VERSION = React

Solution 1:

I had this same problem and solved it by renaming my css file to:

myName.module.css

and also importing like this:

import styles from './myName.module.css'

There is no need to follow the steps of updating the webpack files any more.


Solution 2:

The person in other question was totally right but with a little mistake, without updating the config you can do it. Just put .module in front of your name of css file like that:

myName.module.css

Then call it :

import styles from './myName.module.css'

Working on React 16.6


Solution 3:

in react 16.13 and react-scripts@2.0.0 and higher you don't need to eject your project. Your CSS files must be named camelCase + .modules.css and import to your projects like this:

import React, { Component } from 'react';
import styles from './app.module.css'; // Import css modules stylesheet as styles
class App extends Component {
  render() {
    return <button className={styles.test}>Error Button</button>;
  }
}
export default App;

and in app.module.css

.test{
  color: blue;
}

if you eject projects, in webpack.config.js file, in css modules change like this:

   test: cssRegex,
              exclude: cssModuleRegex,
              use: getStyleLoaders({
                importLoaders: 1,
                sourceMap: isEnvProduction && shouldUseSourceMap,
                modules: true,

Solution 4:

Your CSS files must be named like "yourFileName.module.css". And import into your JS file like below: import yourVariableName from "./yourFileName.module.css";

Works fine on React version:

"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-scripts": "3.1.0"

Solution 5:

I think it will definitely help you out. open config/webpack.config.js and find block like this.

        {
          test: cssRegex,
          exclude: cssModuleRegex,
          use: getStyleLoaders(
            {
              importLoaders: 1,
              sourceMap: isEnvProduction && shouldUseSourceMap,
            },
            'css-loader'
          ),
         sideEffects: true,
        },

and change that like this :

        {
          test: cssRegex,
          exclude: cssModuleRegex,
          use: getStyleLoaders({
            importLoaders: 1,
            sourceMap: isEnvProduction
                ? shouldUseSourceMap
                : isEnvDevelopment,
            modules: {
              getLocalIdent: getCSSModuleLocalIdent,
              localIdentName: '[name]__[local]__[hash:base64:5]'
            }

          }),
          sideEffects: true,
        },

Do same for cssModuleRegex block right after above block and restart your server and you'll get css modules enabled.


Post a Comment for "CSS Modules Not Working For React Version 16.6.0"