How to Fix Cannot find module ‘X’ Error in TypeScript?

When TypeScript cannot find a third-party or local module in our project, the "Cannot find module or its matching type declarations" error occurs.

To resolve the error, ensure that the module is installed and that moduleResolution is set to node in your tsconfig.json file.

Check that you have the module installed if it is a third-party module.

shell

// 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

NOTE:

In your error message, replace module-name with the name of the module.

If you’re encountering issues with a third-party module, try removing your node-modules and package-lock.json files, re-run npm install, and reload your IDE.

shell:

// 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, VSCode frequently malfunctions/glitches and requires a reboot.

If it doesn’t work or TypeScript can’t find your local modules, try to set moduleResolution in your tsconfig.json file to node.

tsconfig.json

{
  "compilerOptions": {
    "moduleResolution": "node",
    // rest of lines
  }
}

More information regarding classic vs node module resolution can be found in the TypeScript documentation.

If it doesn’t work, make sure TypeScript is tracking the module you’re attempting to import. It should be included in your include array and not in your exclude array in your tsconfig.json file.

tsconfig.json

{
  "compilerOptions": {
    // ...
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "src/**/*.spec.ts"]
}

TypeScript will not be able to find the module if it is not in the src directory when using the configuration from the code snippet above.

Check to see that you haven’t already excluded the module by adding it to your exclude array.

If the error message changes to "Could not find declaration file for module'module-name,'” TypeScript has found the module you are attempting to import but cannot locate its type declarations.