How to Use CSS Modules with Create React App

Short answer: you can’t. You gotta ⏏

Ned Schwartz
Feb 5, 2017 · 6 min read
Image for post
Image for post
📎 ⏏ 💿

👉 Here’s how to use CSS Modules with Create React App v2! 👈


$ create-react-app myApp
$ cd myApp/
$ yarn start

Go your own way

Image for post
Image for post
Rumours are that the `eject` command was almost called `break-the-chain`

the `eject` command ⏏

$ yarn eject

Here’s what happens when you eject

$ yarn eject
Are you sure you want to eject? This action is permanent. [y/N]
> y
Ejecting...
Copying files into /Users/user/src/myApp
$ git statusChanges not staged for commit:
modified: package.json
Untracked files:
config/
scripts/

CSS Modules

Image for post
Image for post
We no longer have to think this intensely about CSS.

Installing CSS Modules

Configuring CSS Modules

// before
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
// after
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
modules: true,
localIdentName: "[name]__[local]___[hash:base64:5]"

},
},
// before
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
minimize: true,
sourceMap: true,
},
},
// after
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
modules: true,
minimize: true,
sourceMap: true,
},
},

Update your classNames to use CSS Modules

Before CSS Modules:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;

After CSS Modules:

import React, { Component } from 'react';
import logo from './logo.svg';
import styles from './App.css';
class App extends Component {
render() {
return (
<div className={styles.App}>
<div className={styles.header}>
<img src={logo} className={styles.logo} alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className={styles.intro}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;

You’re on your own now

Further reading


Nulogy

An inside look at our engineering and product culture.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store