How the react project prevents style pollution

React is different from Vue. Vue can limit the effective scope of styles by setting scoped in script, so as not to pollute styles.

The local scope of CSS solves the big problem. In the w3c specification, CSS is always "global". In traditional web development, the biggest headache is to deal with CSS issues. Because of the global nature, the style is clearly defined, but it does not take effect. The reason may be that it is forcibly overridden by other style definitions. Taking over an old project is even more a nightmare. Changing the style of one place but disrupting the style of many other places.

CSS modules are a set of specifications for generating local CSS from the tool level. The essence is to generate a globally unique CSS definition. webpack implements this set of specifications.

  1. The css modules are enabled by default, so we only need to change the name of the original .less or .css file to .module.less
    Example: index.css to index.module.css
//index.module.css
.app {
    
    
  background: red;
}
  1. Introduced in the react js file:
mport index from './index.module.css'
  1. use
<div className={index.App}>
 123
</div>
  1. Inspect,
    Insert picture description here
    you can see that class is the name of a bunch of things. In fact, it is App—<hash value>. This hash value is globally unique, for example, through the file path, so that the class name is globally unique. Through the globally unique CSS naming, we have obtained locally scoped CSS (scoped CSS) in disguise. If a CSS file only serves a certain part, we call such a CSS file a CSS module.

reference

  1. css module

Guess you like

Origin blog.csdn.net/u010682774/article/details/112371932