Cannot find module 'react' Error in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 19, 2022

banner

Photo from Unsplash

Cannot find module 'react' Error in TypeScript #

To solve the "Cannot find module react or its corresponding type declarations" error, install the module and its type definitions by running the commands npm install react and npm i --save-dev @types/react.

cannot find module react

Make sure to install the react module and its type definitions, by opening your terminal in your project's root directory and running the following commands:

shell
npm install react npm install --save-dev @types/react

Now you should be able to import the react library with the following line of code.

index.ts
import React from 'react'; console.log(React);
This should fix the error and now TypeScript should be able to find the type definitions for the react library.

If that doesn't help, 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 the error is not resolved, try to delete your node_modules and package-lock.json files, re-run npm install and restart your IDE.

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

Make sure to restart your IDE if the error persists. VSCode glitches often and a reboot solves things sometimes.

Conclusion #

To solve the "Cannot find module react or its corresponding type declarations" error, install the module and its type definitions by running the commands npm install react and npm i --save-dev @types/react.

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.