TypeScript Support in CSS Modules
What you'll learn: How to generate type definitions for CSS Modules so TypeScript can autocomplete class names and catch typos at compile time.
The Type-Safety Gap
When you import a CSS Module in TypeScript, you get a plain object with string keys—but TypeScript doesn't know what those keys are. You can accidentally write styles.buttno instead of styles.button, and TypeScript won't warn you until runtime. The solution? Automatically generate .d.ts files that define exactly which class names exist in each module.
Two Common Tools
typescript-plugin-css-modules
A TypeScript language service plugin that generates type definitions on-the-fly as you edit. Install it:
npm install -D typescript-plugin-css-modules
Add to tsconfig.json:
{
"compilerOptions": {
"plugins": [{ "name": "typescript-plugin-css-modules" }]
}
}
Now when you import Button.module.css, TypeScript reads the actual CSS file and infers types automatically. Your editor gets full autocomplete for styles.button, styles.primary, etc.
vite-plugin-dts
For build-time generation (especially in library projects), vite-plugin-dts creates .d.ts files during the Vite build:
npm install -D vite-plugin-dts
Configure in vite.config.ts:
import dts from 'vite-plugin-dts';
export default {
plugins: [dts({ include: ['src/**/*.module.css'] })]
};
This outputs declaration files alongside your compiled code, perfect for publishable packages.
Which to Choose
Use typescript-plugin-css-modules for immediate editor feedback during development. Use vite-plugin-dts when building libraries that others will consume. Many projects use both.
Key Takeaway: Generating type definitions for CSS Modules bridges the gap between TypeScript's type system and your stylesheets, giving you autocomplete and compile-time safety for class names.