Having trouble with importing a TypeScript class: encountering a "cannot resolve" error message

Could you lend me your expertise? I'm puzzled by this issue that seems to be quite simple and straightforward:

export class  Rectangle {
      height: number = 0
      width: number  = 0
      constructor(height: number, width: number) {
        this.height = height;
        this.width = width;
      }
    
      // Getter
      get area() {
        return this.calcArea();
      }
      // Method
      calcArea() {
        return this.height * this.width;
      }
    
      public static instance = new Rectangle(2,2)
    }

In main.ts:

import { Rectangle } from './tabs/rectangle' 
const square = new Rectangle(10,10)
console.log("square.area: ", square.area) 

When I run this code, I encounter the following error message:

ERROR in ./src/main/main.ts 36:20-47
Module not found: Error: Can't resolve './tabs/rectangle' in '/home/raphy/Browsering/src/main'
resolve './tabs/rectangle' in '/home/raphy/Browsering/src/main'
  using description file: /home/raphy/Browsering/package.json (relative path: ./src/main)
... (error message continues)

The import of the class works perfectly fine:

import { Rectangle } from './tabs/rectangle'
(base) raphy@pc:~/Browsering$ yarn start
... (output continues)

If I test the same code in Typescript Playground, it runs without any issues:

   class  Rectangle{
    ... (code continues)
  }

... (more code)

console.log(mynewinstance)

Output in the Typescript Playground:

[LOG]: "square.area: ",  100 
[LOG]: "square_2.area: ",  400 
[LOG]: MyNewClass: {} 

I also tried running the code in a CodeSandbox environment, and it worked flawlessly: https://codesandbox.io/s/elegant-driscoll-4yx9z8. So, I am uncertain about why I encounter the error message in my project.

Here is the content of the tsconfig.js file:

     {
      "compilerOptions": {
        ... (options continue)
      },
      "include": ["./src/**/*.ts", "./src/**/*.tsx"],
      "exclude": [
        "src/index.js",
        "dist",
      ]
    }

Additional information:

node : v16.15.0
"typescript": "^4.5.4",
"webpack": "^5.23.0",
"webpack-bundle-analyzer": "^4.4.0",
"webpack-cli": "^4.5.0"
O.S. : Ubuntu 20.04 Desktop

Any insights on how to resolve this issue?

Answer №1

I successfully integrated two tsconfig.json templates into one solution: combining configurations for both node 16 and react.

{
  "$schema": "https://json.schemastore.org/tsconfig",
  "display": "Node 16",

  "compilerOptions": {
    "typeRoots": ["./node_modules/@types"],
    "outDir": "dist",
    "lib": ["es2021", "dom"],
    "module": "commonjs",
    "target": "es2021",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "baseUrl": "./src",
    "moduleResolution": "node",
    "allowJs": true,
    "noImplicitAny": false
  },
  "include": [
    "./src/**/*"
  ],
  "exclude": [
    "src/index.js",
    "dist",
  ]
}

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

Correctly inputting MongoDB-specific collection methods which are currently defaulting to "any"

I'm facing an issue with typing Mongo collection method responses in my app. Specifically, I am having trouble finding a way to type the response of the deleteMany method. The documented response should look like this: { "acknowledged" : true, "delete ...

retrieving a date from a different source and displaying it in a date

Is there a way to ensure that the date format in an input of type date always follows the dd/MM/yyyy Brazilian pattern, regardless of the computer or browser specifications? <div class="input-group input-group text-center in ...

How to use Ionic 3 to automatically scroll ion-scroll content all the way to the bottom

My ion-scroll component is experiencing some challenges <ion-scroll scrollY="true" style="height: 52vh;"> {{ text }} </ion-scroll> The content inside the ion-scroll keeps expanding, exceeding the designated height. Users can manually scroll ...

When res.write is called before res.send, an error occurs

I'm struggling to figure out why I am getting an error with the following code. app.get("/", (req, res) => { res.write("Hello"); res.send(" World!"); }) // Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers afte ...

What is the method for adding attributes to a class dynamically in TypeScript so that they can be accessed by instances?

I attempted to create a universal factory function that generates custom enum objects, but the instances were not able to retrieve the correct properties. Take a look at the preview of the code online: https://stackblitz.com/edit/typescript-rkl1zr Workin ...

Angular Bootstrap Datepicker provides us with a date object, but I need it in the Date format

My desired date format is "Wed Aug 07 2019 16:42:07 GMT+0530 (India Standard Time)", but instead I am receiving { year: 1789, month: 7, day: 14 } from ngbDatepicker. Any assistance on resolving this issue would be greatly appreciated. ...

Prevent modal from closing when clicking outside in React

I am currently working with a modal component in react-bootstrap. Below is the code I used for importing the necessary modules. import React from "react"; import Modal from "react-bootstrap/Modal"; import ModalBody from "react-bootstrap/ModalBody"; impor ...

Switch Object to WebElement or SearchContext in JavaScript

Looking for the best way to convert an Object to WebElement or SearchContext using JavaScript? In Java, casting as `(WebElement)` or `(SearchContext)` works fine. However, attempting the same in JavaScript with `as Webelement` or `as SearchContext` result ...

Employing the CSS not selector within JavaScript

I am facing an issue where my form darkens with the screen every time I click a button to show it, using JavaScript. If I were using CSS, I know I could use the :not selector, but I need guidance on how to achieve this in JS. Can anyone assist me? Below i ...

Transferring PHP data to JQuery through HTML elements

When adding a new comment to the list using PHP variables containing HTML code, the method of choice is typically through JQuery. The question arises - what is the most effective way to achieve this? Would one generally opt for an ajax call? Here's t ...

`In HTML, trigger blocks based on the number chosen by the user`

I am working on creating a web page where users can select the number of friends they have, and based on that input, a corresponding number of invisible boxes will be triggered. For example, if a user selects 3 friends, 3 boxes will appear for them to ente ...

Modifying the maximum length of input fields in HTML, Javascript, and PHP is possible by adjusting the value through

Hi there, I'm facing an issue that should be easy for you guys to help me with. I recently discovered a security flaw while using the maxlength function in HTML. Users can easily modify the maxlength attribute by inspecting elements on the website, wh ...

The message "In Angular, there is no such property as 'data' in the type '{ user: User; session: Session; error: ApiError; }'."

Here is my complete supabase.service.ts code: import { Injectable } from "@angular/core"; import { createClient, SupabaseClient, User } from "@supabase/supabase-js"; import { BehaviorSubject } from "rxjs"; import { envi ...

Retrieving Data in Typescript Async Function: Ensuring Data is Returned Once All Code is Executed

I need help with waiting for data to be retrieved before returning it. The code below fetches data from indexedDB and sends it back to a component. I understand that observables or promises can accomplish this, but I am struggling with how to implement t ...

Vue app showcasing array items through search upon button pressing

As I delve into learning Vue Js, I've encountered a bit of confusion. My goal is to showcase array elements from a Rest API based on the specific ID being searched for. For example: within my Json File are various individuals with unique IDs, and when ...

What is the best way to set up a server in React using Express or HTTP?

I am currently in the process of developing a web application using react js. In order to create a server for my client within the project, I have decided to utilize either express or http. Here is the code snippet that I attempted: import React from " ...

Utilizing jQuery/Javascript to replicate the data from a table while excluding the header and then pasting it to the

I am attempting to replicate the data from a table while disregarding the header/title row and copying it to the clipboard in the exact same way as manual selection and copy. I came across a post on how to choose Select a complete table with Javascript (t ...

Combining two classes into a single class using ‘this’ in JavaScript

I'm encountering an issue where I am unable to figure out how to extend from the third class. So, I really need guidance on how to call the A class with the parameter 'TYPE', extend it with C, and then be able to call getType() with class C. ...

The functionality for accessing objects in Chrome Developer Tools is not functioning properly

Every time I attempt to access an object in Chrome Developer Tools, I encounter the following error message: VM4939:1 Uncaught TypeError: Cannot read property 'cells' of undefined at :1:13 Here is my code: <head> <script> ...

ngRepeat does not completely refresh the DOM when dealing with a basic array

I have a simple array of numbers shown below using ng-repeat: n = [1,2,3,4,5,6] The problem arises when I modify this array, for example: n=[1,2,3] Instead of fully reloading the DOM, only the last 3 div elements corresponding to array 4, 5, 6 are remo ...