Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React, Typescript - Cannot find module ... or its corresponding type declarations

I created a new project using create-react-app and yarn 2 in vs code. The editor throws errors while importing every installed library like this:

Cannot find module 'react' or its corresponding type declarations.

The project compiles and runs successfully but the errors are still there. When I change the file's extension to .js and .jsx from.ts and .tsx, the errors disappear. How should I solve this problem for typescript files?

like image 286
Amir Fakhim Babaei Avatar asked Nov 07 '20 21:11

Amir Fakhim Babaei


People also ask

How do you solve Cannot find module or its corresponding type declarations?

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.

Could not find a declaration file for module react TypeScript?

The error "could not find declaration file for module 'react'" occurs when TypeScript cannot find the type declaration for a react-related module. To solve the error install the types for the module by running the command from the error message, e.g. npm install -D @types/react . Copied!

Can't find module in path react?

To solve the error "Cannot find module 'react/jsx-runtime' or its corresponding type declarations", make sure to install the typings for react running the command npm install --save-dev @types/react@latest @types/react-dom@latest and restart your dev server.

Could not find a declaration file for module react JSX runtime?

When you have this error, it is usually because you installed a library and you didn't install the types of that library. To fix this error, you need to install @types/library-name using your package manager (npm or yarn).


1 Answers

You need to install types for libraries you install. generally you should do:

npm install @types/libName // e.g. npm install @types/react-leaflet 

Some times there's no types available in DefinitelyTyped repo and you encounter npm ERR! 404 Not Found: @types/my-untyped-module@latest. You can do several things in this occasion:

1- Create a decs.d.ts file in root of your project and write in it:

    declare module "libName" // e.g declare module 'react-leaflet' 

2- Or simply suppress the error using @ts-ignore:

// @ts-ignore   import Map from 'react-leaflet' 

3- Or you can do yourself and others a favor and add the library types in DefinitelyTyped repo.

If it still doesn't work, I firstly recommend that you use a recent version of Typescript. if you do, then close your editor, delete node_modules folder and install the dependencies again (npm install or yarn install) and check it again.

like image 181
Mahdi Ghajary Avatar answered Sep 21 '22 15:09

Mahdi Ghajary