skip to Main Content

In my React app (created with create-react-app):

index.js

...
import "@mock/style/css/mock.css";

I want to add a prefix in all css selectors included in the above file. What is the best way to achieve that? Should I use a package like postcss-prefix-selector or Autoprefixer? Should I change Webpack configuration? Not sure about the best approach to follow and not sure how to do that…

2

Answers


  1. PostCss with postcss-prefix-selector is a good choice for your case, and yes, you should change your webpack config. But it is quite simple too, here it is.

    Login or Signup to reply.
  2. You can maybe use css modules. This means that you change the file extension of a .css file to .module.css. Then you can import and use it like this:

    import styles from '@mock/style/css/mock.module.css';
    
    <p className={styles.redText}>Hello this text is red</p>
    

    The css module file would look something like this:

    .redText{
      color:red;
    }
    

    You can name the styles import however you want. In a module css file all the rules have to be for classes or id’s you can’t use it to style all p elements for example.
    For more information you can look at the documentation from react: css modules react.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search