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?
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.
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!
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With