Typescript error: Module not found or its corresponding type declarations cannot be located

After setting up a new project using create-react-app and yarn 2 in my vs code environment, I encountered an issue where the editor throws errors for every installed library. The error message I receive is:

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

Despite the project compiling and running successfully, these errors persist. Interestingly, changing the file extensions from .ts and .tsx to .js and .jsx makes the errors disappear. How can I resolve this problem specifically for typescript files?

Answer №1

Perhaps simply restarting the TypeScript server could resolve the issue.

If using VsCode:

For Windows users:

Type: ctrl + Shift + P or ctrl + Shift + F5

Select:

> TypeScript: Restart TS server

For Macbook users:

Type: ⇧ + ⌘ + P or F1

Select:

> TypeScript: Restart TS server

It's possible that there may be a file error, so check if you accidentally changed a file extension from .ts to .tsx or .tsx to .ts.

Answer №2

When installing libraries, make sure to also install the corresponding types. Here's what you can do:

npm install @types/libName // for example: npm install @types/react-leaflet

Sometimes, you may not find types available in DefinitelyTyped repository and encounter

npm ERR! 404 Not Found: @types/my-untyped-module@latest
. In such cases, you have a few options:

1- Create a decs.d.ts file at the root of your project and add:

    declare module "libName" // for example: declare module 'react-leaflet'

2- Alternatively, you can suppress the error using @ts-ignore:

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

3- Another option is to contribute the library types to DefinitelyTyped repository.

If the issue persists, try updating to a newer version of Typescript. If that doesn't work, close your editor, delete the node_modules folder, reinstall dependencies with either npm install or yarn install, and then check again.

Answer №3

I encountered a similar error message, which was also related to imports.

The issue in my case stemmed from importing a png file for use in an SVG:

import logo from 'url:../../public/img/logo.png';

The specific error message I saw was:

Cannot find module 'url:../..public/img/logo.png' or its corresponding type declarations.

Solution:

Within the project root directory, there is a file named css.d.ts. It is necessary to declare a module for different graphic extensions (types) that are being imported. (Please note: this is not for graphics types used within the project, but specifically for those being imported )

Below is the contents of the complete css.d.ts file for this project:

declare module '*.scss' {
  const css: { [key: string]: string };
  export default css;
}
declare module '*.sass' {
  const css: { [key: string]: string };
  export default css;
}
declare module 'react-markup';
declare module '*.webp';
declare module '*.png';
declare module '*.jpg';
declare module '*.jpeg';

Answer №4

my current problem:

myFolder is located within the src directory

I am encountering the same issue on this particular line of code:

import { GlobalStyle } from "myFolder";

none of the other suggested solutions are effective.

To resolve this, I simply appended baseUrl to the tsconfig.json file beneath compilerOptions:

{
  "compilerOptions": {
    "baseUrl": "src/",
//other configurations...
  },
  "include": [
    "src"
  ]
}

problem resolved successfully!

reference: https://www.typescriptlang.org/tsconfig#baseUrl

Answer №5

After removing and re-adding a module to my source code, I encountered an error due to caching even though the source code remained the same.

Here is the solution that worked for me:

For Windows users:

Press ctrl + Shift + F5

For Macbook users:

Press ⇧ + ⌘ + P OR F1

https://i.sstatic.net/f9n2w.png

Answer №6

The problem was resolved successfully

  1. Make a new file named /types/css.d.ts
  2. Access the file tsconfig.json

Insert the following block:

"include": [
    "src",
    "types"
]

Answer №7

When I encountered this issue, I realized that my file was named index.tsx, but it should have been with a capital I. Therefore, the correct name should be Index.tsx.

Answer №8

This issue persists even with the latest yarn + PnP versions, as a result of a known bug. Reference

  1. Delete any previous SDKs typescript folder located at .yarn/sdks/typescript
  2. Install the previous supported version of TypeScript:
    yarn add <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2e232a3f293928332a2e1a6e746d">[email protected]</a>
  3. Include the new editor SDKs by running: yarn dlx @yarnpkg/sdks vscode. You can also add vim or any other supported SDKs.
  4. Restart your integrated development environment (IDE)

Answer №9

To address this issue, I implemented the following import statement in my solution: "/index.cjs": import { MRT_Localization_RU } from "mantine-react-table/locales/en/index.cjs";

Answer №10

To refresh your project in VSCode, simply select: > TypeScript: Reload Project

It did the trick for my setup.

Answer №11

To find the necessary dependencies, refer to the dependencies object in the package.json file. If the package you are installing is in the format "@somepackage/packagename": version; then when importing, make sure to use import abc from "@somepackage/packagename"

If "@somepackage/" is not included, avoid using it during import. Simply import as follows: import abc from "packagename";

Answer №12

During my experience, I unknowingly imported an autocomplete (such as "@reduxjs/toolkit/src/query/tests/mocks/server") that was added by VS Code and went unnoticed until the commit.

Answer №13

I was faced with this issue and managed to resolve it by relaunching the TypeScript compiler:

npm install ts-node --save-dev
npm install typescript -g
npm install typescript --save-dev

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the intricacies of the let and const modifiers in ngFor loops

I encountered some unexpected behavior with the const keyword while using it in an Angular 2 *ngFor loop. Let's consider the following base code: interface Foo { name: string; list: string[]; } @Component({ ... }) class FooComponent() { ...

Creating reducers for a unique data type: A step-by-step guide

Today, I was working on enhancing a shopping website using React Typescript and Context API. My goal is to utilize React Reducers to manage the state of my Shopping Cart. I have custom Types defined for the Product type, which includes an Items Array and s ...

Using React to Identify the Chosen Option on a Custom Toggle Button

I have successfully implemented a toggle switch using HTML and CSS in my React app. I am now looking for a way to detect the selected option whenever it changes. For instance, if OR is chosen, I would like it to be saved in the selectedOption state, and if ...

Angular: Implementing a Dark and Light Mode Toggle with Bootstrap 4

Looking for suggestions on the most effective way to incorporate dark mode and light mode into my bootstrap 4 (scss) angular application. Since the Angular cli compiles scss files, I'm not keen on the traditional method of using separate css files for ...

A guide on passing an ngFor object variable to a function

I am trying to display subcategories for each category in my *ngFor list. The subcategory data is retrieved from Firebase using the category_id, but I am struggling to pass the category_id from the HTML to the function for every member of the category. ho ...

Tips for resolving these dependency issues

After updating my Angular and my Angular project version to Angular 7, I encountered an issue when trying to run it: The package "@angular/compiler-cli" has an incompatible peer dependency with "typescript" (requires ">=3.1.1 <3.2", but would instal ...

Errors TS2585 and TS2304 encountered during compilation of TypeScript file using Axios

What steps should I take to fix the errors that arise when attempting to compile my TypeScript code using tsc index.ts? node_modules/axios/index.d.ts:75:3 - error TS1165: In an ambient context, a computed property name must reference an expression of lite ...

Building a customized Mui clip with child support: A step-by-step guide

Looking to create a customized chip that can handle both single and nested declarations? Check out this example using MUI v5. interface StyledModalChipProps { theme: Theme children: React.ReactNode } export const StyledModalChip = styled(Chip)<Styled ...

A comprehensive guide on utilizing the ngFor directive for looping through objects

After trying to iterate over this dataset within my HTML, I attempted a nested ngfor, but unfortunately encountered an error. My attempt involved iterating the object twice with a nested ngfor, resulting in the following error: HabitRecordsComponent.ht ...

exclude a few countries from ngx-intl-tel-input

I'm facing an issue where I need to remove certain countries, like Mexico, from the list displayed in ngx-intl-tel-input. Even after trying the 'excludeCountries' option, it doesn't seem to be working for me. Below is a snippet of my ...

Error: The function 'describe' has not been defined in the Karma jasmine angular2 environment

Struggling with writing tests using Jasmine and Karma in my Ionic project V2. All necessary packages have been added, but I'm still encountering the issue "describe is not defined". Can anyone offer assistance? Thank you. Here's my karma.conf.js ...

Creating a Utils class in Vue.js with seamless access to Vuex through this.$store

I have a situation where I need to retrieve state from the Vuex store using this.$store. After some research, I discovered that creating a custom plugin with an installed instance method might be the solution. Here is my plugin implementation: index.ts i ...

Unable to find the correct path in my NodeJS/Express/Typescript application

Having trouble with my '/api/users' route that doesn't seem to be properly defined in my routes setup. When attempting to access /api/users from the browser, it just sticks in a repeated loop. app.ts import * as express from "express" impo ...

Navigating Circular Relationships in TypeScript

Herein lies a question about statically inferring the signature of runtime types, as seen in popular libraries like zod and io-ts. If you want to see an example in action, check out this TS playground link. Let's say we're attempting to model t ...

The declaration file for the module 'react-tilt' was not located

After following the installation and import steps for react-tilt as outlined in this guide, I encountered the following error message and am unable to utilize it. I'm uncertain about what the message implies. Is there anyone who can help me resolve th ...

How can I extract a value from an object that is readonly, using a formatted string as the key?

I encountered a situation where I have code resembling the following snippet. It involves an object called errorMessages and multiple fields. Each field corresponds to various error messages in the errorMessages object, but using a formatted string to retr ...

What could be causing Angular to replace the original variable?

As a newcomer to Angular, I've been working on this code for hours now. Hopefully, it will all come together for someone out there who can make sense of it. export class QuizComponent implements OnInit { originalArray: IArray[] = []; tempArray: I ...

"Enhance your Vue 3 projects with a dynamic library featuring universal components and full

Currently, I am in the process of developing a Vue 3 component library using Vue 3, Vite, and TypeScript. The unique aspect about this library is that it installs as a plugin and registers all components as global entities. Here is an overview of how this ...

Error encountered: NextJs could not find the specified module, which includes Typescript and SCSS

I am in the process of migrating a Next.js application from .js to .ts and incorporating ScSS. The first error I encounter is during 'npm run dev'. However, when I try 'npm run build', different issues arise that do not seem related to ...

Error: Unable to access the 'secondary' property of an undefined object - encountered after updating Material-UI from version 4 to version 5

We recently completed an upgrade from MUI version 4 to version 5, and since the upgrade, our UI tests have been failing with the following error: TypeError: Cannot read property 'secondary' of undefined (I added comment to which line in code thi ...