Thomas KiTe Trentin
Thomas KiTe Trentin

Reputation: 600

Load CSS module in ReactJS + Typescript and react rewired

I'm creating the initial setup of a proof of concept project using ReactJS and typescript, and I'd like to include the CSS modules in it without having to eject the webpack configuration.

Here are the steps I followed so far:

I correctly set my App.module.scss file, and referenced it in my App.tsx file:

import styles from './App.module.scss';

When I run the project, I have an error regarding the css module: Cannot find module './App.module.scss'.

When I do the exact same project without the typescript configuration, it works though.

What should I change for the CSS modules to be taken into account?

I came accross typings-for-css-modules-loader, but I'm not sure how to integrate it in my configuration since I didn't eject the webpack configuration.

Thanks in advance,

Thomas .T

EDIT 1: I added a global.d.ts file with:

And it did the trick. I didn't use typings-for-css-modules-loader in the end.

The answer comes from this article: https://hackernoon.com/zero-config-react-typescript-css-modules-jest-with-poi-bbcedfe2383a

Upvotes: 4

Views: 6278

Answers (2)

Rakesh Swain
Rakesh Swain

Reputation: 31

I got the workaround after googling a lot. I'm new to react js and trying to build using typescript so I found the solution and started using

react-script-ts

package. But when I started using css module faced the problem import class from './button.css' didn't work so I used import './button.css' but in this got lot of css conflicts, higher component scope css always overridden by lower component. so googled a lot and finally got the solution.

Solution From 2.1 create-react-app having support for typescript so convert your application to 2.1 above

1.create new application using `npx create-react-app my-new-app --typescript`
2. replace your old src folder in new solution
3. Rename all your css file with `*.module.css` and change the import based on that.
4. Add your package dependancy if anything missing
5. Run

source : https://joshblog.net/2018/upgrading-a-react-and-typescript-app-from-react-scripts-ts-to-create-react-app-v2-1/

Upvotes: 1

Thomas KiTe Trentin
Thomas KiTe Trentin

Reputation: 600

I added a global.d.ts file with:

  • declare module '*.css'
  • declare module '*.scss'

And it did the trick. I didn't use typings-for-css-modules-loader in the end.

The answer comes from this article: https://hackernoon.com/zero-config-react-typescript-css-modules-jest-with-poi-bbcedfe2383a

Gonna accept this as an answer within 2 days.

Upvotes: 4

Related Questions