CSS Modules allows us to write CSS code in a modular way, and these styles can be imported and used in JavaScript files. Using CSS Modules can automatically generate unique class names, isolate styles between different modules, and avoid class name conflicts.
Rsbuild supports CSS Modules by default, you don't need to add additional configuration. Our convention is to use the [name].module.css
filename to enable CSS Modules.
The following style files are considered CSS Modules:
*.module.css
*.module.less
*.module.sass
*.module.scss
*.module.styl
*.module.stylus
If you prefer to use named imports in CSS Modules, you can enable it through the output.cssModules.namedExport config.
If enabled, you can reference class names using named imports:
By default, only files ending with *.module.css
are recognized as CSS Modules.
If you want to treat other CSS files as CSS Modules as well, you can achieve this by configuring output.cssModules.auto.
For example:
After this configuration, the following two files will be recognized as CSS Modules:
Customizing the class names generated by CSS Modules is also a commonly used function, you can use output.cssModules.localIdentName to configure it.
If you need to customize other configs of CSS Modules, you can set them via output.cssModules.
When you import CSS Modules in TypeScript code, TypeScript may prompt that the module is missing a type definition:
To fix this, you need to add a type declaration file for the CSS Modules, please create a src/env.d.ts
file, and add the corresponding type declaration.
@rsbuild/core
package is installed, you can reference the preset types provided by @rsbuild/core
:After adding the type declaration, if the type error still exists, you can try to restart the current IDE, or adjust the directory where env.d.ts
is located, making sure the TypeScript can correctly identify the type definition.
Although the above method can provide the type of CSS Modules, it cannot accurately prompt which classNames are exported by a certain CSS file.
Rsbuild supports generating accurate type declarations for CSS Modules, you only need to register the @rsbuild/plugin-typed-css-modules, and then execute the build, Rsbuild will generate type declaration files for all CSS Modules.
For example, create two files named src/index.ts
and src/index.module.css
:
After building, Rsbuild will generate a src/index.module.css.d.ts
type declaration file:
Now when you open the src/index.ts
file, you can see that the styles
object already has an accurate type.