Reference Documents:

CSS Modules tutorial – Ruan Yifeng

Prerequisites: React scaffolding project, using Antd UI component library

Webpack configuration:

// webpack.config.js
module.exports = {
  rules: [{test: /\.less$/,
      use: [
        {
          loader: 'style-loader'
        },
        {
          loader: 'css-loader'.// translates CSS into CommonJS
          options: {
            modules: true // Enable CSS Modules}}, {loader: 'less-loader'.// compiles Less to CSS
          options: {
            lessOptions: {
              // If less-loader@5 is used, remove the lessOptions level of the direct configuration option.
              modifyVars: {
                'primary-color': '#1DA57A'.'link-color': '#1DA57A'.'border-radius-base': '2px'
              },
              javascriptEnabled: true}}}]/ /... other rules}]/ /... other config
};
Copy the code

Rewrite Antd component styles:

// TestPage.ts
import { Select } from 'antd';
import styles from './TestPage.less';
const Option = Select.Option;

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i} >{i.toString(36) + i}</Option>);
}

ReactDOM.render(
  <Select
    mode='multiple'
    style={{ width: 300 }}
    placeholder='Please select'
    className={styles.customSelect}>
    {children}
  </Select>,
  mountNode
);
Copy the code
// TestPage.less
.customSelect{:global {
    .ant-select-selection {
      max-height: 51px;
      overflow: auto; }}}Copy the code

When CSS Modules is enabled,

Import styles from ‘**/*.less’ as import styles from ‘**/*.less’

ClassName ={styles. ClassName} or className={styles[className]} for class names,

Class names generate Hash strings that appear in the DOM class.


Use :global(.className) {// Your CSS Code… }

Or :global {.className {// Your CSS Code… }} syntax,

Declare a global rule that the className will not be compiled into a hash string.

Use this syntax to implement Antd component style rewriting.


Note: In the example above, the global rule declared by global is restricted to the customSelect class, so that it only applies to customSelect and does not pollute the world.