How to use css modules with create-react-app? How to use css modules with create-react-app? reactjs reactjs

How to use css modules with create-react-app?


You do not need to eject.

Create React App supports CSS Modules right out of the box as of version 2.

Upgrade to the latest (react-scripts@latest) version.

If you use yarn:

yarn upgrade react-scripts@latest

If you use npm:

npm install --save react-scripts@latest

Then you just have to create a file with the extension .module.css

For example:

.myStyle {  color: #fff}

Then you can use it like so:

import React from 'react'import styles from './mycssmodule.module.css'export default () => <div className={styles.myStyle}>We are styled!</div>


To enable CSS module in to your app, you don't need to eject create-react-app. You can follow these simple steps described in this link to use CSS module in your project.

But in case if you ejected your create-react-app, then you must find file named

"webpack.config.js"

open this file and find this {test:cssRegex....etc} in line no. 391 and replace to this changes:

            {              test: cssRegex,              exclude: cssModuleRegex,              use: getStyleLoaders({              importLoaders: 1,              modules: true,              localIdentName: '[name]__[local]__[hash:base64:5]'            }),            },

Open .js file and import statement like this

import cssStyleClassName from './MyApp.css';

Then this import statement allow you to do following changes in component tags like this

<div className={cssStyleClassName.styleName}></div>

styleName is what you defined in your MyAppStyle.css file

.styleName{your properties here...}

After eject your app, you must restart your local server, sometime changes don't get reflect.

Note In earlier version there were two generated file for production and dev separately. Now in current version one file named "webpack.config.js" file for which you need to concerned for changes. Thank you.


You are using version 1.1.4 , so CSS Modules doesn't work by default ... above version 2.0, it works default by changing the css file name to name.module.css.