CSS Modules in create-react-app v2

To Enable CSS Modules in create-react-app in v1 required bit of extra work. We have to eject the app there using “npm run ejectand then write these following lines of code in config/webpack.config.dev.jsafter searching for ‘css-loader’ section.

/ 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]"

},
}

The same code has to put also in “config/webpack.config.prod.js” file in same ‘css-loader’ section.

// 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,
},
}

And then You can import the Stylesheet like this and use:

import classes from './SomeComponent.css’;
<div className={classes.someClassName}></div>

But Now in create-react-app v2, CSS Modules works out of the box. We dont need to follow all those tedious steps anymore. We only have to name that stylesheet like ‘MyStyleSheet.module.css’. Here we attach “.module” keyword before the stylesheet name. I hope the following example will clear how we use CSS Modules now.

Rename the stylesheet from ‘./SomeComponent.css’ to ‘./SomeComponent.module.css’ and use like this:

import classes from './SomeComponent.module.css’;
<div className={classes.someClassName}></div>

That’s it.

Leave some claps if this article helped you in any way :)

Developer? Trying to be One! Work: https://play.google.com/store/apps/developer?id=Amandeep+Kochhar