When TSC suddenly errors with cannot find module
Warning
TLDR
- If you have this error, double-check if your
rootDiris consistent. - I got this error from TSC, auto-flattening the folder structure.
My TypeScript Node server suddenly threw this on tsc with production settings.
I stashed my work and went back in time with git checkout HASH. Turns out the error started when I added MongoDB models at src/models.
It seemed strange since it had nothing to do with adding new modules or dependencies. Reinstalling node_modules did not do the job for me (relevant Stack Overflow question). Here's my folder structure.
Long story short, it was the problem in my tsconfig. I have previously declared the following statement on my tsconfig.
However, since there was only a /server folder before creating the model, it seems that TSC has automatically set the root directory to src/server. Therefore the dist output seemed like the following.
Then models/user.ts showed up, so src held both models and server, and TSC took src as the root. Now it looked like this.
Notice the directory structure has changed. My entire npm commands were based as if src/server was a root directory (as if the index was at dist/index.js), so that began to cause the error. Therefore I updated the npm commands. Note that I changed dists to dist/servers.
To prevent TSC from guessing the root directory, you can add the following line on your tsconfig.json.
This line will retain the absolute folder structure from src.