. Advertisement .
..3..
. Advertisement .
..4..
Are you having difficulties with “Cannot find module ‘X’ Error” in TypeScript? Don’t worry! In this article, we will help you understand the cause of it and give you some solutions to fix this issue. Let’s start!
What is the root cause of this error?
When you run your program, you easily get the following error:
Cannot find module 'X' Error
“Cannot find module ‘X’ Error” appears when TypeScript cannot locate a local or third-party module in the script.
How to fix “Cannot find module ‘X’ Error” in TypeScript?
Take a look at the example below:
// install the required module using the npm install command
npm install module-name
// here it saves the module
npm install --save-dev @types/module-name
Check to be clear that the module is enabled and moduleResolution is set to a node in the tsconfig.json file to fix the error. If it’s a third-party module, make sure you get it installed.
If a third-party module is causing you trouble, consider deleting your node-modules and package-lock.json files, performing npm install again, and refreshing your IDE.
// remove the node modules using the rd and rm commands and also from package-lock.json
rm -rf node_modules package-lock.json
// run npm install command to install all the modules which are in the package.json
npm install
Reload your IDE since VSCode frequently crashes or has bugs and needs to be restarted. If it fails or TypeScript cannot find the local modules, consider setting moduleResolution to a node in your tsconfig.json file by using these commands.
{
"compilerOptions": {
"moduleResolution": "node",
// rest of lines
}
}
Check if TypeScript is monitoring the module you’re importing if it also doesn’t work. In your tsconfig.json file, it must appear in the include array instead of the exclude array.
{
"compilerOptions": {
// ...
},
"include": ["src/**/*"],
"exclude": ["node_modules", "src/**/*.spec.ts"]
}
When utilizing the configuration from the preceding code snippet, TypeScript cannot locate the module if it is not stored in the src directory.
Add the module to your exclude array to ensure you haven’t previously excluded it.
In case the error message appears, “Could not find declaration file for module “module-name,” Even though you were attempting to import a module, TypeScript could not identify its type declarations.
As you can see, solve the problem step by step, and we can fix the error perfectly.
Conclusion
We hope you have found the best way to resolve it whenever you see the error “Cannot find module ‘X’ Error” in TypeScript on our page. If there are any other problems with this error, please comment below, and we will reply as soon as possible! Thank you for reading!
Read more
→ How To Fix “Error: Cannot find module ‘express’” In Node.Js
Leave a comment