When TSC suddenly errors with cannot find module
TLDR
- If you have this error, double-check if your
rootDiris consistent. - I got this error from TSC, auto-flattening the folder structure.
On my TypeScript Node Server, I suddenly got the following error on the tsc command for production settings.
Then I stashed my work and started traveling back in time with git checkout HASH. Comes 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). Please take a look at 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.
But after models/user.ts was added, src contained both models and server directories, recognizing the root directory as src. So it now became:
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.