Setting Up CSS Modules
You'll learn how to configure CSS Modules in modern build tools so your styles work seamlessly with component-based architectures.
What Configuration Involves
CSS Modules don't work out of the box—they require build tool support to transform your locally-scoped class names into unique identifiers. Think of the setup like installing a translator: you write human-friendly class names, and the build tool converts them into collision-proof versions at compile time.
File Naming Conventions
Most build tools recognize CSS Modules through specific file naming patterns:
Standard convention: Component.module.css
The .module.css extension signals to your bundler: "treat this file as a CSS Module." Without it, the file is processed as regular global CSS.
Configuration in Vite
Vite supports CSS Modules by default with zero configuration. Any file ending in .module.css automatically gets Module treatment:
// vite.config.js - default behavior, no config needed
export default {
css: {
modules: {
// Optional: customize generated class names
generateScopedName: '[name]__[local]___[hash:base64:5]'
}
}
}
Configuration in Webpack
Webpack requires explicit loader configuration:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.module\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: {
localIdentName: '[name]__[local]--[hash:base64:5]'
}
}
}
]
}
]
}
}
The localIdentName option controls how your scoped class names appear in the compiled output—useful for debugging.
Key Loader Options
Both tools support customizing how class names are generated, whether source maps are enabled, and how :global() selectors behave.
Key Takeaway: CSS Modules require build tool configuration through file naming conventions (.module.css) and loader options that control class name generation and scoping behavior.