How to Fix “cannot find module CSS/SCSS” in TypeScript

The error “cannot find module CSS/SCSS” occurs when TypeScript is “having trouble understanding how to handle CSS or SCSS files in your project.” This can happen because TypeScript, by default, understands only JavaScript and TypeScript files and doesn’t know how to handle other file types like CSS or SCSS.

Here’s a step-by-step guide to fix this error:

Step 1: Install Type Definitions (if using CSS Modules)

If you use CSS Modules, you might want to install type definitions for them. You can do this using the typings or @types packages. For example:

npm install --save-dev @types/css-modules

Step 2: Modify the tsconfig.json File

You can tell TypeScript how to handle CSS or SCSS files by adding a wildcard module declaration in your tsconfig.json file.

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "*": ["src/types/*"]
     }
   }
 }

Step 3: Create a Declaration File

Create a new “.d.ts” file (e.g., declarations.d.ts) in your project, and add the following declarations:

For CSS

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

For SCSS

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

You can place this file in the directory mentioned in the paths option in the “tsconfig.json” file (e.g., src/types).

Step 4: Import the CSS/SCSS Files Correctly

Ensure you are correctly importing the CSS or SCSS files in your TypeScript files.

Here’s an example:

import styles from './myStyles.css';

Here is an example of how to import an SCSS file in TypeScript:

import './styles.scss';

The styles.scss file should be located in the same directory as the file where you are importing it.

Step 5: Restart Your Development Server

If you use a development server like webpack-dev-server, restart it to apply the changes.

I hope these steps will fix your error!

Related posts

cannot find module and its corresponding type declarations

TypeScript getting error TS2304: cannot find name ‘ require’

Leave a Comment