27 Nov 2018 • 2 min read
I was working on a React project and I kept running into an error that read Cannot find module './Index.module.scss'
. The file was definitely there, and the project was building fine. What gives?
After doing more research, it turns out that this isn’t a problem with missing files at all, but missing type definitions. For whatever reason, when Typescript reads the file, realizes it doesn’t have type definitions, and instead of saying something like “Missing type definitions for file”, it says that it can’t find it at all. To fix this error, you need to take two steps:
tsconfig.json
file.scss
filesThis step is pretty straightforward — just add a file named tsconfig.json
to the top level of your project. You can have Typescript automatically generate one (with the command tsc --init
), but here’s an example of a basic one to get you started:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"jsx": "react",
"strict": true,
"esModuleInterop": true
}
}
If you decide to have Typescript automatically generate one, just make sure you set the jsx
option to react
.
Random tidbit: you can actually fix this error with a blank tsconfig
file. While that’s an option, I think it makes sense to populate it with actual values, so you don’t have some random blank file hanging around. You also then have more control over how your Typescript is compiling.
There are three approaches to solving this problem:
.scss
files (hard because the tooling out there isn’t perfect).scss
files (easy)After spending hours on trying to make #2 work, I decided to go with option #3. To do this, you create a .d.ts
file somewhere in your project (I stuck mine in the src
folder and called it globals.d.ts
) and add the following definition to it:
declare module '*.scss' {
const content: {[className: string]: string};
export = content;
}
This declaration basically tells Typescript what to expect when looking at a .scss
file. Save that and then…
Get my posts in your feed of choice. Opt-out any time.
If you enjoyed this article, you might enjoy one of these: