The goals:
- The component can be published to npmjs.org
- No need to incldude css manually on page
- Instead of using inline css, now we use Class Name
Think about that you made an awesome React component, you don’t just want to use it in your own project but also want to publish
to npm
to share with others. However, awesome ui can not live without css. So you either use a bunch of inline css, or write in
the README to tell people who use this component to also include an external css file. This is really not a good idea to write
isolate React Component.
Here we introduce CSS Modules. The idea is that you can import
a css file as it is
a normal npm
module. In the we will use react-css-modules
1 | import styles from './style.css'; |
Then you can use the css class name in your jsx
code. for example in our example you will find:
1 | class Progress extends Component { |
You use styleName
attribute and the value is just the pure class name you defined in style.css.
Finally, you will need to wrap the component with CSSModules
1
export default cssModules(Progress, styles);
Basically that’s it. But in order to make this component works, you will need to do some webpack settings.
1 | { |
find more from the source code