Sub topic 12
Bundler and framework support
CSS Modules are not a browser feature. A build tool reads each .module.css file, rewrites the class names, and hands your JavaScript an object that maps the names you wrote to the names it generated. This chapter covers which tools do that work, what they need from you, and the errors you will see when something is misconfigured.
This chapter assumes you know basic React, can read a bundler config file, and have already imported a .module.css file as shown in earlier chapters.
What the tool has to do
Every tool that supports CSS Modules performs the same three jobs:
- It recognizes which files are modules. The usual rule is the
.module.csssuffix. - It transforms the CSS. Each local class name is replaced with a unique name, and the result is emitted as a normal stylesheet.
- It exports a JavaScript object. The default export of the import maps each original class name to its generated name.
Because the bundler does this work at build time, no runtime library is needed. The cost is that your tool must be configured to do it, and the details differ between tools.
Vite
Vite supports CSS Modules with no setup. Any file ending in .module.css is treated as a CSS Module. The same applies to .module.scss, .module.sass and .module.less once the matching preprocessor is installed.
A minimal component works as soon as the project is created:
import styles from './Button.module.css';
export function Button({ children }) {
return <button className={styles.button}>{children}</button>;
}You can change how names are generated through the css.modules option in vite.config.js. Vite passes these options to the postcss-modules plugin.
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
css: {
modules: {
// Use camelCase keys in the styles object for kebab-case class names.
localsConvention: 'camelCaseOnly',
// Readable names in development help when inspecting the DOM.
generateScopedName: '[name]__[local]___[hash:base64:5]',
},
},
});With localsConvention: 'camelCaseOnly', a class written as .primary-button is available as styles.primaryButton and is not available under its original key. Use 'camelCase' if you want both keys.
webpack
webpack does not understand CSS at all until you add loaders. A typical setup uses css-loader to process the CSS and either style-loader (injects <style> tags, good for development) or mini-css-extract-plugin (writes a real .css file, good for production).
// webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const isProd = process.env.NODE_ENV === 'production';
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
isProd ? MiniCssExtractPlugin.loader : 'style-loader',
{
loader: 'css-loader',
options: {
modules: {
auto: true,
localIdentName: isProd
? '[hash:base64:8]'
: '[name]__[local]--[hash:base64:5]',
},
},
},
],
},
],
},
plugins: [new MiniCssExtractPlugin()],
};The important option is modules.auto. When it is true, css-loader treats files matching /\.module\.\w+$/i as CSS Modules and treats every other .css file as global CSS. This lets one rule handle both kinds of file. Without auto, setting modules: true would make every CSS file a module, including a global reset or a third-party stylesheet, and their class names would be rewritten.
Recent css-loader versions export named exports by default in some configurations. If import styles from ... gives you undefined or an unexpected shape, check the modules.namedExport and modules.exportLocalsConvention options in the version you have installed.
Create React App
Create React App follows the same convention as Vite. A file named Something.module.css is a CSS Module, and a plain Something.css is global. No configuration is needed, and the webpack configuration is hidden. Create React App is no longer actively developed, so for new projects Vite or a framework is the usual choice. Existing CRA projects still work with the pattern shown in this tutorial.
Next.js
Next.js has built-in support for CSS Modules. Both the App Router and the Pages Router accept .module.css imports in components.
// app/dashboard/Card.jsx
import styles from './Card.module.css';
export function Card({ title, children }) {
return (
<section className={styles.card}>
<h2 className={styles.title}>{title}</h2>
{children}
</section>
);
}Two framework rules matter here:
- Plain global CSS has restricted placement. In the Pages Router, global stylesheets can only be imported from
pages/_app.js. In the App Router, they are normally imported from the root layout. CSS Modules have no such restriction. You can import them from any component, which is a main reason to prefer them for component styling. - Selectors must be "pure". Next.js requires that every selector in a CSS Module contain at least one local class or id. A rule like
h1 { margin: 0 }on its own is rejected at build time. You will see a message that the selector is not pure. The next section explains the fix.
Server Components can import CSS Modules without any extra step. The styles are collected on the server and sent with the page.
Fixing "not pure" selector errors
A bare element selector is global, so it breaks the guarantee that a module only affects its own component. Next.js enforces this. Attach the element selector to a local class:
/* Rejected: no local class in the selector */
h1 {
margin: 0;
}
/* Accepted: scoped through .card */
.card h1 {
margin: 0;
}Other tools do not enforce this rule. In Vite or webpack the bare h1 rule compiles and applies to every h1 on the page. The pattern is a bug in any tool, and Next.js simply reports it.
Sass and other preprocessors
CSS Modules and preprocessors combine. Name the file Button.module.scss, install sass, and import it the same way. The preprocessor runs first, and then the CSS Modules step rewrites class names.
// Button.module.scss
$brand: #2563eb;
.button {
background: $brand;
&:hover {
background: darken($brand, 8%);
}
&.large {
padding: 1rem 2rem;
}
}Nested selectors such as &.large produce .button.large. Both button and large appear in styles, so styles.large works.
PostCSS and the module pipeline
Both Vite and Next.js run PostCSS on CSS Module files if a PostCSS config exists. Plugins such as Autoprefixer apply to the module's CSS before or alongside class renaming. You do not configure this per file. A postcss.config.js at the project root is enough.
Choosing a naming pattern
The generated name pattern is a trade-off.
| Environment | Suggested pattern | Reason |
|---|---|---|
| Development | `[name]__[local]--[hash:base64:5]` | Shows the file and the class name in browser devtools. |
| Production | `[hash:base64:8]` or the tool default | Shorter names make smaller HTML and CSS. |
| Snapshot tests | A stable pattern or a mock | Hashes can change between builds and break snapshots. |
Next.js and Vite already pick sensible defaults, so you only need to change the pattern if you have a specific reason such as debugging or deterministic snapshots.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| `styles.button` is `undefined` | The class does not exist in the file, or the key was renamed by a camelCase option | Log `styles` and compare the keys with your CSS |
| `styles` is an empty object or `undefined` | The file is not named `.module.css`, or the loader is not treating it as a module | Rename the file or set `modules.auto` in `css-loader` |
| Class names are not changed in the DOM | The file was processed as global CSS | Check the file suffix and loader rules |
| Build error: "Selector is not pure" | A selector has no local class (Next.js) | Combine it with a local class or use `:global` deliberately |
| Global CSS stops working after a config change | `modules: true` applies to every CSS file | Use `modules.auto: true` |
| Styles missing in production only | The extraction plugin is not configured for production | Verify `mini-css-extract-plugin` in the production build |
A quick verification
A short test confirms that your setup works. Create a module and a component, then render it and check the DOM.
/* Badge.module.css */
.badge {
display: inline-block;
padding: 0.125rem 0.5rem;
border-radius: 999px;
background: #e5e7eb;
}// Badge.jsx
import styles from './Badge.module.css';
console.log(styles); // { badge: "Badge_badge__x7Ke2" } or similar
export function Badge({ children }) {
return <span className={styles.badge}>{children}</span>;
}In the browser, inspect the element. Its class should be a generated name that contains badge, not the plain string badge. If it is the plain string, the file was handled as global CSS.
Exercise
A project uses webpack with css-loader and the option modules: true. After adding a third-party stylesheet named vendor.css, its class names stop matching the markup the library produces. What is the cause, and what configuration change fixes it?
Show answer
With modules: true, css-loader treats every CSS file as a CSS Module, so the class names in vendor.css are rewritten to hashed names. The library's markup still uses the original names, so the rules no longer match. Set modules: { auto: true } so that only files matching the .module.* pattern are treated as modules and vendor.css stays global.
Exercise
In a Next.js project, this rule in Layout.module.css fails the build: a { color: inherit; }. Why does it fail, and give two ways to make it valid.
Show answer
Next.js requires pure selectors, meaning each selector must contain at least one local class or id. A bare a selector is global. Make it valid by scoping it under a local class, such as .nav a { color: inherit; }, or by marking it global on purpose with :global(a) { color: inherit; }, which is only appropriate if a global rule is really intended.