Cannot find module 'X' Error in TypeScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Cannot find module 'X' Error in TypeScript #

The "Cannot find module or its corresponding type declarations" error occurs when TypeScript cannot locate a third-party or local module in our project. To solve the error, make sure to install the module and try setting moduleResolution to node in your tsconfig.json file.

If the module is a third-party module, make sure you have it installed.

shell
npm install module-name npm install --save-dev @types/module-name
Make sure to replace module-name with the name of the module in your error message.

If it is a third-party module you're having problems with, try removing your node-modules directory and your package-lock.json file, re-run npm install and reload your IDE.

shell
rm -rf node_modules package-lock.json npm install

Make sure to reload your IDE as VSCode often glitches and needs a reboot.

If that doesn't help or TypeScript can't locate your local modules, try setting moduleResolution to node in your tsconfig.json file.

tsconfig.json
{ "compilerOptions": { "moduleResolution": "node", // 👇️ ... rest } }

You can read more about classic vs node module resolution in the TypeScript docs.

If that doesn't help, make sure the module you are trying to import is tracked by TypeScript. It should be covered in your include array setting and not be present in the exclude array in your tsconfig.json file.

tsconfig.json
{ "compilerOptions": { // ... }, "include": ["src/**/*"], "exclude": ["node_modules", "src/**/*.spec.ts"] }
For example, if the module is out of the src directory whilst using the configuration from the code snippet above, TypeScript would not be able to find it.

Make sure you haven't excluded the module by adding it to your exclude array.

If your error message changes to "Could not find declaration file for module 'module-name'", then TypeScript has located the module you are trying to import, but can't find its type declarations.

If that is the case, check out my other article Could not find declaration file for module 'X' Error.

Conclusion #

The "Cannot find module or its corresponding type declarations" error occurs when TypeScript cannot locate a third-party or local module in our project. To solve the error, make sure to install the module and try setting moduleResolution to node in your tsconfig.json file.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.