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

北慕城南 提交于 2019-11-30 00:07:14

You do not need to eject.

Create-React-App supports css modules right out of the box as of version 2, which is now stable.

Upgrade to v2 (react-scripts@latest) by running yarn upgrade react-scripts@latest.

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 need to eject create-react-app and then in config files for webpack you add these 2 lines

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 */
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!