Cannot find scss module error when compiling Typescript file in React application
In Create React App V2.0, you can use scss module / css module. If you use scss module in Typescript file e.g. React Typescript Component, firstly let me show you an example how to use scss module in Typescript file.
Scss module name follows the following naming convention .[filename]\_[classname]\_\_[hash].
In browser, you will see class name e.g. .Example_main__i348.
🤔But, when you compile Example.tsx file, you will see the following error:
src/components/Example/Example.tsx:3:20 — error TS2307: Cannot find module ‘./Example.module.scss’.
3 import styles from ‘./Example.module.scss’;
🤔What happened? Well, it lacks scss module type definition.
A quick solution for this issue is using 🎁 typed-css-modules.
Typed-scss-modules
Generate TypeScript definitions (.d.ts) files for CSS Modules that are written in SCSS (.scss)
Since the type definitions should only be generated during development, we need to install the package as a development dependency.
yarn add -D typed-scss-modules
Now, the types definition can be generated by providing the directory or glob pattern. Let us try run:
yarn tsm src/
We will see the file Example.module.scss.d.ts is generated. Open Example.module.scss.d.ts file, we can see the content like below:
export const main: string;
Now if you compile Example.tsx, you will not get the previous error.
Typed-css-modules
Similarly, you can consider Typed-css-modules if you are using css modules.
Typed-css-modules creates TypeScript definition files from CSS Modules .css files.
More Latest Articles
How to export and read env variables when running Serverless offline?
Mar 17th
When you develop Serverless applications on AWS, it would be handy to run Serverless offline for testing and debug. Normally, Serverless applications need to pick up env variables from the .env file.
Serverless, AWS, env,dotenv
An element descriptor’s .kind property must be either “method” or “field”
Mar 8th
An element descriptor’s .kind property must be either “method” or “field” when upgrade to Babel 7 from Babel 6.
Serverless, React, Webpack, Babel 7,decorators