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

2019-02-06 00:40发布

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

2条回答
Luminary・发光体
2楼-- · 2019-02-06 01:09

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>
查看更多
欢心
3楼-- · 2019-02-06 01:29

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 */
}
查看更多
登录 后发表回答