“Believe in yourself && Keep Learning”

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

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.

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

Before:-

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

After:-

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

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

Before:-

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

After:-

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

Step4:-Implementing CSS modules,

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

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(
            <div className={styles.header}>
               {children}
            </div>
        );
    }
}

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

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

Example code using both css modules and global classes.

import classnames from 'classnames';
import styles from './test.module.scss';
<Button
          className={classnames('button', 'button-primary', styles.login)}
          type="submit"
        >
Test Button
</Button>

Leave a Reply

Your email address will not be published. Required fields are marked *