Webstorm+TypeScript cannot resolve SCSS modules in CRA project (Error TS2339)

Viewed 966

I have a have a Create React App project that I'm currently migrating over from FlowJS to TypeScript. When I integrated TypeScript into the project, a problem that has arisen within WebStorm is that TypeScript cannot seem to resolve any keys from SCSS module imports. I always get greeted with the following:

TS_SCSS_Error

My top level styles import is: import styles from './_styles.module.scss'

After doing a lot of research/digging into trying to resolve this issue, I have a created a src/global.d.ts file that contains the following:

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

Despite having the above module defined, invalidating caches and restarting WebStorm, the problem still persists -- I no longer know what else to try in order to resolve this problem.

My TypeScript version is set to "typescript": "^3.8.3" within my package.json. And this is what my tsconfig.json looks like:

{
  "compilerOptions": {
    "allowJs": false,
    "allowSyntheticDefaultImports": true,
    "baseUrl": "src",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noImplicitAny": false,
    "outDir": "./build",
    "plugins": [
      { "name": "typescript-plugin-css-modules" }
    ],
    "removeComments": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "target": "es5"
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx"
  ],
  "exclude": ["node_modules"]
}

Any help with this will be greatly appreciated.

1 Answers

seems like typescript didn't pick up the definitions in src/global.d.ts, try to add src folder as a typing root folder in tsconfig.json, and restart typescript.

{
  "compilerOptions": {
    ...
    "typeRoots" : ["src", "node_modules/@types"]
  }
}

more details: @types, typeRoots and types

Related