output.cssModules

  • 类型:
type CSSModules = {
  auto?:
    | boolean
    | RegExp
    | ((
        resourcePath: string,
        resourceQuery: string,
        resourceFragment: string,
      ) => boolean);
  localIdentName?: string;
  exportLocalsConvention?: CSSModulesLocalsConvention;
};

用于自定义 CSS Modules 配置。

Rsbuild 的 CSS Modules 功能是基于 css-loader 的 modules 选项实现的,你可以参考 css-loader - modules 来了解更多。

cssModules.auto

auto 配置项允许基于文件名自动启用 CSS 模块。

  • 类型:
type Auto =
  | boolean
  | RegExp
  | ((
      resourcePath: string,
      resourceQuery: string,
      resourceFragment: string,
    ) => boolean);
  • 默认值: true

类型说明:

  • true: 为所有匹配 /\.module\.\w+$/i.test(filename) 正则表达式的文件启用 CSS 模块。
  • false: 禁用 CSS 模块。
  • RegExp: 为所有匹配 /RegExp/i.test(filename) 正则表达式的文件启用 CSS 模块。
  • function: 为所有通过基于文件名的过滤函数校验的文件启用 CSS 模块。
export default {
  output: {
    cssModules: {
      auto: (resource) => {
        return resource.includes('.module.') || resource.includes('shared/');
      },
    },
  },
};

cssModules.exportLocalsConvention

导出的 class 名称的命名风格。

  • 类型:
type CSSModulesLocalsConvention =
  | 'asIs'
  | 'camelCase'
  | 'camelCaseOnly'
  | 'dashes'
  | 'dashesOnly';
  • 默认值: 'camelCase'

类型说明:

  • asIs 类名将按原样导出。
  • camelCase 类名将被驼峰化,原始类名仍然可用。
  • camelCaseOnly 类名将被驼峰化,原始类名不可用。
  • dashes 只有类名中的破折号会被驼峰化,原始类名仍然可用。
  • dashesOnly 只有类名中的破折号会被驼峰化,原始类名不可用。
export default {
  output: {
    cssModules: {
      exportLocalsConvention: 'camelCaseOnly',
    },
  },
};

cssModules.localIdentName

  • 类型: string
  • 默认值:
// isProd 表示生产环境构建
const localIdentName = isProd
  ? '[local]-[hash:base64:6]'
  : '[path][name]__[local]-[hash:base64:6]';

设置 CSS Modules 编译后生成的 class names 格式。

默认值

localIdentName 在开发环境和生产环境有不同的默认值。

在生产环境,Rsbuild 会生成更简短的类名,从而减少构建产物的体积。

import styles from './index.module.scss';

// 在开发环境下,值为 `src-index-module__header-[hash]`
// 在生产环境下,值为 `header-[hash]`
console.log(styles.header);

模板字符串

localIdentName 中,你可以使用以下模板字符串:

  • [name] - 源文件名称。
  • [local] - 原始类名。
  • [hash] - 字符串的哈希值。
  • [folder] - 文件夹的相对路径。
  • [path] - 源文件的相对路径。
  • [file] - 文件名和路径。
  • [ext] - 文件后缀名,包含点号。
  • [hash:<hashDigest>:<hashDigestLength>] - 带有哈希设置的哈希。

示例

localIdentName 设置为其他值:

export default {
  output: {
    cssModules: {
      localIdentName: '[hash:base64:4]',
    },
  },
};

cssModules.exportGlobals

  • 类型: boolean
  • 默认值: false

允许从 global class names 导出名称,以便你可以通过 import 使用它们。

示例

exportGlobals 设置为 true

export default {
  output: {
    cssModules: {
      exportGlobals: true,
    },
  },
};

在 CSS Modules 中使用 :global()

style.module.css
:global(.blue) {
  color: blue;
}

.red {
  color: red;
}

然后你可以导入 :global() 包裹的类名:

Button.tsx
import styles from './style.module.css';

console.log(styles.blue); // 'blue'
console.log(styles.red); // 'red-[hash]'