CSS Modules add local scope and module dependencies to CSS.

One: local scope

When working on a SPA project, all CSS would be packaged into main.css and referenced globally, which would be terrifying. You can’t know the impact of all the CSS combinations, and it’s hard to pinpoint problems.

So it’s important that CSS applies to local scopes, and how to do that is to give a class a unique name that doesn’t have the same name as any other class.

And CSS Modules do just that.

A React multicast diagram component

index.less:

.main { color: red; }

Index. JSX:

import { Carousel } from 'antd-mobile';
import styles from './index.less';

const carouselImgs = [];

export default () => {
  return (
    <Carousel className={styles.main} autoplay={true} infinite>
      {carouselImgs.map(item => (
        <img src={item.src} alt={item.alt} />
      ))}
    </Carousel>
  );
};

Copy the code

What happens if we import the index.less file into the styles object and use the class with styles.main?

Obviously, styles.main is compiled to a hash string. The main class will not have the same name, and it will achieve the desired result.

Two: global scope

So what if we want the class not to compile into a hash, but to be used globally?

CSS Modules provide the :global syntax, so classes declared like this are not compiled.

.king { color: blue; }}Copy the code

<div className="king">king</div>

It’s exactly what we thought! Perfect! Note, however, that you cannot use styles.king when using a global class, otherwise it will not compile.

Three: Define variables

.king {
  @blueCOlor: #0c77f9;
  color: @blueCOlor;
}
Copy the code

We can also define variables for reuse.

Four: class combination

.colorRed{
  color: red;
}

.king {
  composes: colorRed
}
Copy the code

We can use comPoses to combine classes for inheritance.

Five: Introduce other modules

.king {
  composes: colorYellow from './test.less'
}
Copy the code

We can combine classes by introducing them in other style files.