Reputation: 8147
When using [email protected] with css modules enabled and namedExports
on, is there a way to wildcard import the file in Typescript and have the resulting type of each named export be a string?
// webpack.d.ts
declare module '*.module.css' {
export = Record<string, string>; // still contains the default export.
}
Edit: Ideally, there wouldn't be a default
export present on the module when importing.
Upvotes: 2
Views: 1002
Reputation: 2472
You can't declare exports that way since they disabled arbitrary expressions here. Instead declare and type a const and export it.
declare module '*.module.css' {
const value: Record<string, string>;
export default value;
}
As far as I could find there is no way to have named exports declared arbitrarily. But you could just use the shorthand ambient module declaration and declare the module twice. It does mean you won't get entire type safety since this will make all named exports any
but I couldn't find anything else.
declare module '*.module.css'
declare module '*.module.css' {
// this type is from react-scripts https://github.com/facebook/create-react-app/blob/main/packages/react-scripts/lib/react-app.d.ts
// it is better since the data is immutable
const classes: { readonly [key: string]: string };
export default classes;
}
And in another file
import { someclass } from 'some.module.css';
// ^ typeof any
I believe the best solution if you really want strict type safety is to have a build-step that generates a .d.ts for all the css modules.
.SomeComponent { height: 10px; }
becomes
declare const styles: { readonly SomeComponent: string; }; export = styles;
Upvotes: 2