How to make module css works with typescript in a gatsby application?
Asked Answered
L

2

7

I have an GastbyJS application, and I'm trying to add typescript on it. I solve most of the issues, but I'm not able to make the css module work with it.

I have this import in my file, that works fine:
import styles from "./card.module.css"

But when I added the typescript config it says that Cannot find module './card.module.css'.ts(2307)

I tried to use some gatsby plugins, but they didn`t work as expected.

The whole code is here: github

Libelous answered 23/4, 2020 at 3:18 Comment(2)
Maybe you can add gatsby-plugin-typescript inside tsconfig.json plugins.Seidel
what version of gatsby are you using?Doordie
D
9

I had the same problem and after trying all the various plugins I came across this solution which worked for me.

Create a css.d.ts file with:

declare module '*.css' {
    const content: { [className: string]: string };
    export default content;
}

Add these lines to your tsconfig.json file:

"esModuleInterop": true,
"files": ["./src/typings/css.d.ts"]

The "files" path needs to match where your type definition file is.

https://github.com/thetrevorharmon/gatsby-starter-typescript-sass/issues/1#issuecomment-436748732

Dematerialize answered 11/6, 2020 at 19:21 Comment(1)
What would be the equivalent procedure if you have a .jsconfig instead?Stash
P
0

After trying multiple plugins, I recommend using gatsby-plugin-dts-css-modules (tested on Gatsby v5).

Install

npm install gatsby-plugin-dts-css-modules --save-dev
# or
yarn add gatsby-plugin-dts-css-modules --dev

Config

// gatsby-config.ts
const config: GatsbyConfig = {
    // ...
    plugins: [
        // ...
        `gatsby-plugin-dts-css-modules`, // add support for CSS modules with TypeScript
    ]
};
Pertain answered 30/4 at 5:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.