What You'll Learn
You'll learn how to configure CSS Modules in a Vite-powered React project—spoiler: they work automatically with the .module.css naming convention.
CSS Modules Work Out-of-the-Box in Vite
Here's the best part about using CSS Modules with Vite: you don't need to configure anything. Vite recognizes CSS Modules automatically when you follow a simple naming convention.
Any CSS file ending in .module.css is treated as a CSS Module by Vite's built-in preprocessing pipeline. This means styles are automatically scoped to your component without any webpack configuration, build tool setup, or additional plugins.
The Naming Convention
Think of the .module.css extension as a secret handshake between your CSS file and Vite. When Vite sees that .module in the filename, it knows to:
- Process the file as a CSS Module
- Generate unique class names to prevent collisions
- Export an object you can import in JavaScript
How It Works in Practice
Create a file named Button.module.css:
.primary {
background: blue;
color: white;
}
.secondary {
background: gray;
}
Then import it in your component:
import styles from './Button.module.css';
function Button() {
return <button className={styles.primary}>Click me</button>;
}
Vite handles the transformation behind the scenes. The class name .primary becomes something like Button_primary_a8c3d in the browser—completely scoped and collision-free.
No Configuration Required
Unlike older setups that required webpack loaders or complex build configurations, Vite treats CSS Modules as a first-class citizen. Just name your file with .module.css and start importing.
Key Takeaway: Vite supports CSS Modules out-of-the-box—just use the .module.css naming convention, and you're ready to go with zero configuration.