How to use css modules with create-react-app?
Asked Answered
T

11

53

According to a tweet by Dan Abramov, CSS modules support is there in create-react-app (CRA). One just needs to give extension of module.css to his stylesheets to enable the feature, but this is not working with me. I am having version 1.1.4 of react-scripts. How can I enable css modules with CRA? Thanks

Tamayo answered 8/5, 2018 at 13:32 Comment(3)
It's only available on cra v2. See github.com/facebook/create-react-app/pull/2285Joanjoana
did you manga to figure out how to get your app to display correctly on firebase? yarn upgrade react-scripts@latest yielded the same results after i uploaded the new build.Subjective
almost every answer here: "no problem, lets get rid of cra by ejecting it first". Seriously?Demello
A
125

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>
Apocalyptic answered 2/7, 2018 at 3:21 Comment(2)
I'm using [email protected] and it doesn't work. Am i using the good version of react-scripts ?Burkhart
@Emidomh next major version will start with 2. Run the command I wrote in the answer if you would like to upgrade. You can see the versions hereApocalyptic
M
11

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.

Mastoiditis answered 26/3, 2019 at 10:6 Comment(2)
New to react here. I think I ejected my create-react-app. I don't have a webpack.config.js file only webpack.config.dev.js and webpack.config.prod.js inside config folder. Do I make webpack.config.js file in the root and add what code?Confucius
this solution will not work with react-scripts version larger than 2, you should use this solution : create-react-app.dev/docs/adding-a-css-modules-stylesheetCheapskate
S
2

i am using 3.4.1 version of the react-scripts so here is my approach

  1. run the command :npm run eject 2.Then you will get a config file , in that open webpack.config.js
  2. And search test: cssRegex or just search cssRegex
  3. now you will see something like this:
test: cssRegex,
              exclude: cssModuleRegex,
              use: getStyleLoaders({
                importLoaders: 1,
                sourceMap: isEnvProduction && shouldUseSourceMap,
              }),

now after importLoaders:1, add modules:true, and just save the file. 5.Now you can restart the server using npm start and you will see your styles applied. (if you already know them how to use)

here when I used [name]__[local]__[hash:base64:5] because I got an error that

 - options has an unknown property 'localIdentName'. These properties are valid:
   object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }


so I removed it and I just used modules:true and it worked for me.

Spalato answered 20/6, 2020 at 11:32 Comment(2)
I tried so hard to find this :( It works and Thank you. :)Paymar
new update, it even works without these settingsSpalato
T
2
  1. Run the command npm run eject
  2. Open the webpack.config.js file.
  3. Find test: cssRegex section and edit it like following:
{
  test: cssRegex,
  exclude: cssModuleRegex,
  use: getStyleLoaders({
    importLoaders: 1,
    sourceMap: isEnvProduction
      ? shouldUseSourceMap
      : isEnvDevelopment,
    modules: {
      // mode: 'icss',
      getLocalIdent: getCSSModuleLocalIdent,
    },
  }),
Twelfthtide answered 24/2, 2021 at 11:55 Comment(0)
G
1

You need to eject create-react-app and then in config files for webpack you add these 2 lines enter image description here

And to use it load css to Component you wan't (i keed component and it's css in same folder)

import classes from './SomeComponentStyle.css';

...

<div className={classes.RedDiv}>

inside SomeComponentStyle.css

.RedDiv {
  /* styles for red div */
}
Groceryman answered 8/5, 2018 at 13:39 Comment(0)
W
1

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.

Wirehaired answered 13/11, 2019 at 11:1 Comment(0)
C
0

Depending on your react-scripts version (you can check the version in package.json file):

For react-scripts version before 2.0.0:

  1. if you are using git in your project you should commit your changes and push them.

  2. do npm run eject

  3. edit your webpack config files dev and prod with these changes: webpack config changes

  4. if you are running your app, stop it and rerun it, hence you will find your changes and can then use CSS modules.


Starting with react-scripts version 2.0.0:

You can follow "Adding a CSS Modules Stylesheet" from the official create-react-app documentation.

Cheapskate answered 28/3, 2020 at 17:41 Comment(0)
P
0

Heading ##i use react-script version 3.4.3 (latest version). you simply follow the below given steps.

run the command :npm run eject

Then you will get a config file , in that open webpack.config.js

And search test: cssRegex or just search cssRegex now you will see something like this:

test: cssRegex,

          exclude: cssModuleRegex,
          use: getStyleLoaders({
            importLoaders: 1,
            sourceMap: isEnvProduction && shouldUseSourceMap,
          }),

now after importLoaders:1, add modules:true, and just save the file.

Now you can restart the server using npm start and you will see your styles applied.

Open .js file and import statement like this

import cssStyleClassName from './MyAppStyle.css';

please do not forget to add .css extension to the styling file, at the time of import.

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...
}
Parulis answered 16/8, 2020 at 11:43 Comment(1)
Its not wise to eject just to use css modules, you will lose all the updating you get from using create react app, and will need to manage all the depndencies yourselfGobbledygook
F
0
In webpack.config.js file find this keyword 'css-loader'.
You will find below code in line number 82 for react version-16.13
{
   loader: require.resolve('css-loader'),
   options: cssOptions,      
}

Replace above object with 

{
   loader: require.resolve('css-loader'),
   options: {
      modules: {
        mode: "local",
        localIdentName: "[name]_[local]_[hash:base64:5]"
      },
      import: true,
      importLoaders: true
    }     
}

Start the server again by npm start(If changes are not reflected)
Fulsome answered 10/10, 2020 at 11:59 Comment(0)
R
0

There is a fresh library called patch-styles package.

It's introducing a more declarative way of applying styles. You need to wrap your code with <PatchStyles classNames={style}> where style is the default import from the style module. See the example of usage in StackBlitz.

Riband answered 27/12, 2020 at 20:8 Comment(0)
A
0

With React-17.0.2, Run below script

npm run eject

Go to file

webpack.config.js

Search for

cssRegex

Add module object as below

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

Then your css file will work with name Eg. header.css

Ame answered 18/11, 2021 at 19:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.