Sub topic 13
Typing CSS Module imports in TypeScript
This chapter assumes you can write React components in TypeScript, you have a working .module.css setup from the earlier chapters, and you know what tsconfig.json does. Runtime behavior of CSS Modules is not repeated here. The chapter covers only how the type checker sees a CSS Module import.
Why the import fails without help
The compiler only understands files it can resolve to TypeScript or JavaScript. A bundler such as Vite or webpack turns import styles from './Button.module.css' into an object at build time. The compiler never sees that step, so it reports an error like this:
TS2307: Cannot find module './Button.module.css' or its corresponding type declarations.Your app may still run, because the bundler handles the import. The error is only the type checker saying it has no description of what the import returns. There are two ways to supply one:
- A wildcard module declaration that covers every
*.module.cssfile. - A per-file declaration that lists the real class names.
Option 1: a wildcard declaration
The smallest fix is an ambient declaration. It states that any import ending in .module.css is an object that maps class names to strings.
declare module '*.module.css' {
const classes: { readonly [key: string]: string };
export default classes;
}Save it in a file such as src/types/css-modules.d.ts. The readonly modifier stops you from assigning to styles.button by accident. Assigning would be a bug, because the bundler owns that object.
Why the file must stay a script
This file must not contain a top-level import or export. Once it does, TypeScript treats it as a module. The declare module '*.module.css' line then becomes a module augmentation instead of an ambient declaration. Augmentation of a wildcard name fails or is ignored, and the original TS2307 error comes back. If you need to import a type inside the declaration, put the import inside the declare module block.
Make sure the compiler reads the file
A .d.ts file only counts if the compiler includes it. Check that your tsconfig.json include covers the folder.
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"isolatedModules": true,
"skipLibCheck": true,
"noEmit": true
},
"include": ["src"]
}If the declaration lives outside src, add its folder to include. Otherwise editors and tsc disagree about whether the error exists.
What the wildcard type gives you, and what it costs
With the wildcard declaration, every property access returns string. That has two consequences.
- Autocomplete shows nothing useful. The editor cannot list
buttonorprimary. - A typo is not caught.
styles.butontype-checks, evaluates toundefinedat runtime, and the element silently loses its style.
Here is the result in practice:
import styles from './Button.module.css';
export function Button({ label }: { label: string }) {
// Compiles, but styles.buton is undefined at runtime.
return <button className={styles.buton}>{label}</button>;
}React omits the class attribute when className is undefined, so you get an unstyled button with no error. The failure is worse if you build the class with a template string, such as ` ${styles.buton} large . That produces the literal class undefined large`.
If you turn on noUncheckedIndexedAccess, the index signature returns string | undefined. Passing that to className is still valid, because className accepts undefined. The flag therefore changes the type but does not catch the typo.
Types supplied by your framework
Most frameworks already ship a wildcard declaration, so you may not need to write one.
| Tool | Where the declaration comes from |
|---|---|
| Vite | `/// <reference types="vite/client" />` in `src/vite-env.d.ts` |
| Next.js | `next-env.d.ts`, which references `next/types/global` |
| Create React App | `react-app-env.d.ts`, which references `react-scripts` |
| Plain webpack | You write the declaration yourself |
The built-in declarations use the same loose shape as the wildcard above. Sass files need their own entries (*.module.scss, *.module.sass), and some frameworks provide those as well.
Do not duplicate a declaration that already exists. Two wildcard declarations for the same pattern merge, which is usually harmless. If they disagree about the shape, for example one says string and the other string | undefined, you get confusing errors.
Option 2: exact types per file
If you want autocomplete and typo detection, generate a declaration for each CSS Module file. It lists the real class names.
TypeScript 5.0 added the allowArbitraryExtensions option. It lets an import such as ./Button.module.css resolve to a sibling declaration file named Button.module.d.css.ts. Turn the option on:
{
"compilerOptions": {
"allowArbitraryExtensions": true
}
}The generated file looks like this:
declare const styles: {
readonly button: string;
readonly primary: string;
readonly secondary: string;
readonly disabled: string;
};
export default styles;Now styles.buton is an error, and the editor completes styles. with the four real names. The naming rule is the part people get wrong. For Name.module.css the declaration is Name.module.d.css.ts. It is not Name.module.css.d.ts.
Where the generated files come from
You normally do not write these by hand. Two common tools produce them:
typed-css-modules(thetcmcommand) writes declaration files next to each stylesheet. Run it in watch mode during development and once in CI. Its output format and file naming depend on its options, so check that it matches the.d.css.tsconvention above.typescript-plugin-css-modulesis a language service plugin. It gives editors autocomplete and error squiggles without creating files. It does not affecttsc, so a command-line build or CI run will not see the plugin's checks.
Whichever you pick, decide whether to commit the generated files. Committing them keeps CI simple but adds noisy diffs. Ignoring them means CI must run the generator before tsc.
Which option to choose
| Concern | Wildcard declaration | Generated per-file types |
|---|---|---|
| Setup effort | One small file | A generator and a build step |
| Typo detection | None | Yes, at compile time |
| Autocomplete | None | Yes |
| Stale files | Not possible | Possible if the generator is not rerun |
| Dynamic keys like `styles[variant]` | Always type-checks | Checks only if the key type matches the class names |
For a small app, the wildcard is fine. The generated types pay off when many people edit many stylesheets and renamed classes keep breaking silently.
Dynamic keys and variants
The variant pattern from earlier chapters looks up a class by name: styles[variant]. Under the wildcard type, any string is a valid key. Under generated types, the key must be a known class name, so you can tie the prop type to the stylesheet:
import clsx from 'clsx';
import styles from './Button.module.css';
type ButtonProps = {
variant?: 'primary' | 'secondary';
disabled?: boolean;
children: React.ReactNode;
};
export function Button({
variant = 'primary',
disabled = false,
children,
}: ButtonProps) {
return (
<button
className={clsx(styles.button, styles[variant], disabled && styles.disabled)}
disabled={disabled}
>
{children}
</button>
);
}If you later add a 'danger' variant to the union but forget the .danger class, the generated types report an error on styles[variant]. The wildcard type does not.
Custom properties and the style prop
Custom properties from the dynamic-values chapter hit a separate typing problem. React's CSSProperties type lists known CSS properties, and --progress is not one of them. The cast is the usual workaround:
import type { CSSProperties } from 'react';
import styles from './Progress.module.css';
export function Progress({ value }: { value: number }) {
return (
<div
className={styles.bar}
style={{ '--progress': `${value}%` } as CSSProperties}
/>
);
}The cast silences the checker for the whole object, so a misspelled standard property in the same object would also pass. Keep custom-property objects small and separate from other inline styles.
Named exports and other loader settings
Everything above assumes a default export. Some setups, such as css-loader with esModule and namedExport enabled, expose each class as a named export instead. You then write import * as styles from './Button.module.css', and the wildcard declaration must change to match. Check your bundler's output before copying a declaration. The type must describe what the bundler actually emits.
Common mistakes
- Adding
importorexportat the top of the wildcard declaration file, which turns it into a module. - Putting the declaration outside the
includepaths. - Naming a per-file declaration
Button.module.css.d.tsand expectingallowArbitraryExtensionsto find it. - Forgetting
*.module.scsswhen the project uses Sass. - Treating the wildcard type as proof that a class exists.
Exercise
Your project uses TypeScript 5 and has Card.module.css. You add declare module '*.module.css' in a file that begins with import type { CSSProperties } from 'react';, and TS2307 still appears for Card.module.css. What is wrong, and how do you fix it?
Show answer
The top-level import makes the file a module, so the declaration is treated as an augmentation and not as an ambient wildcard declaration. Remove the top-level import and, if the type is needed, import it inside the declare module block. Also confirm the file is covered by include in tsconfig.json.
Exercise
You enable allowArbitraryExtensions and generate exact types for Alert.module.css. What must the declaration file be named, and what happens if a component then reads styles.warnng (a typo)?
Show answer
The file must be named Alert.module.d.css.ts. The typo produces a compile-time error because warnng is not a key of the generated type. Under the wildcard declaration, the same code would compile and return undefined at runtime.