How to add CSS modules into your react Application? – User friendly Tech help

n

“Believe in yourself && Keep Learning”

n

n

Step1:- In our example we have take “create-react-app” template as reference. Install this and than perform “yarn eject

n

What is yarn eject:- it will give you control of the create-react-app and you can install or play with config settings or package.json file.

n

Step2:- Search for “css-loader” inside the file “config/webpack.config.dev.js” and enable CSS modules in this.

n

Before:-

n

 require.resolve('style-loader'),n              {n                loader: require.resolve('css-loader'),n                options: {n                  importLoaders: 1,n                },n              },

n

After:-

n

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

n

Step3:- Change it for production file also(“config/webpack.config.prod.js” )

n

Before:-

n

  loader: require.resolve('css-loader'),n                      options: {n                        importLoaders: 1,n                        minimize: true,n                        sourceMap: shouldUseSourceMap,n                      },

n

After:-

n

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

n

Step4:-Implementing CSS modules,

n

use >  import styes from ‘filename’ and than className={styles.class}

n

import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styles from './ToolTip.css'; export default class ToolTip extends Component { static displayName = "ToolTip"; static propTypes= { children: PropTypes.node.isRequired, } render(){ const {children} = this.props; return( n               {children}n            n        );n    }n}

n

Step5:- yarn start
nNow React app is happily married to CSS modules.

n

Note:- Incase you are facing issue with using global classes and CSS modules together you can use “ClassNames”

n

Example code using both css modules and global classes.

n

import classnames from 'classnames';nimport styles from './test.module.scss';nnTest Buttonn
Was this article helpful?
YesNo

Similar Posts