Home > Software engineering >  Cannot find module "@src/styles.scss"
Cannot find module "@src/styles.scss"

Time:06-22

I import the style file in my project like this:

import styles from '@src/styles.scss';

The tsconfig.json file contains:

{
"compilerOptions": {
    "module": "CommonJS",
    "target": "ES5",
    "jsx": "react",
    "baseUrl": "./",
    "paths": {
        "@src/*": ["src/*"]
    }
},
"include": ["src"],
"exclude": ["node_modules"],
"compileOnSave": false
}

But my Visual Studio Code is throwing error Cannot find module "@src/styles.scss". Although the assembly of the project occurs without errors. The styles.scss file does exist and is located in the src folder.

In the project I use webpack 5 and I have already specified aliases in its config.

Can you please tell me how to solve this visual problem?

CodePudding user response:

Following our chat, I think that the reason IntelliSense is not working is that typescript paths look for .js(x)/.ts(x) extensions (which is not the case of .scss). The reason it works at build time is that webpack is taking care of it.

I recommend using a solution like module-alias to get rid of this warning on VSCode.

CodePudding user response:

After a few days of searching for a solution, I still found it! The whole problem is that typescript only accepts files with .js(x)/.ts(x) extensions as modules.

Therefore, we need to manually specify that files with the .scss extension are also modules.

Create a typings folder in the root of the project. In this folder, create a declarations.d.ts file with the contents:

declare module '*.scss' {
  const content: Record<string, string>;
  export default content;
}

Now in the tsconfig.json file, add the typings folder:

{
  ...
  "include": ["typings", "src"],
}

I hope my answer saves someone time!

  • Related