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

Retrieving information from a database by employing AngularJS with the assistance of PHP

I am a beginner in using AngularJS and I am trying to retrieve data from a database using PHP. Here is the code I have tried: <html> <head> <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.2 ...

Defining Array Types in TypeScript JSON

My attempt at coding a class in TypeScript has hit a roadblock. Whenever I try to utilize Jsons in an Array, the system crashes due to a TypeScript error. Here's the class I tried to create: class Api { url: string | undefined; credentials: Ar ...

What is the best way to make an image expand when clicked, align it in the center of the webpage, and have it return to its original position with just one more click by utilizing

Currently, this is the code I am working with. The JavaScript functionality is working well, however, there seems to be an issue where the image does not return to its original size on a second click. Additionally, I am having trouble getting the CSS to ce ...

Utilizing Node.js and Jasmine: Preventing the invocation of a Promise function to avoid executing the actual code results in DEFAULT_TIMEOUT_INTERVAL

There is a function below that returns a promise. public async getAverageHeadCount(queryParams: Params, childNode: any, careerTrackId: string): Promise<Metric> { const queryId = this.hierarchyServiceApiUrl + "rolling-forecast/ahc/" + q ...

Discovering descendant div elements

I've been conducting some research, but I'm struggling to find a specific answer for this. Here is the HTML code snippet: <div class="collapsingHeader"> <div class="listItemWrapper"> <div class="itemWrapper"> ...

Transform the string property extracted from the API into a JSON object

When making a request to an API, the data returned to the front end is in the following format: { name: 'Fred', data: [{'name': '"10\\" x 45\\" Nice Shirts (2-pack)"', 'price' ...

The specified 'Object' type does not match the required 'Document' constraint

I need assistance with running a MERN application to check for any issues, but I keep encountering this error across multiple files. Error: The 'CatalogType' type does not meet the requirements of 'Document'. The 'CatalogType&apo ...

What is the method for extracting a variable from a URL using JavaScript?

For instance, consider this URL- website.com/page/?var=20 I am looking to extract the "var" variable from the URL using JavaScript. By the way, my actual URL is- https://bipit2.pranaypro21292.repl.co/d21292auth/?code=pimWoHEuV7fgKEVQMTntRnzXqVla3G&gu ...

Send a function as a parameter to another component, but it remains dormant

I am attempting to control the enable and disable state of a button based on changes in a value. To achieve this, I have defined a model as follows: export class Model{ label:string=''; isEnabled:Function=()=>true; } The component1 i ...

Guide on dynamically importing a module in Next.js from the current file

I am facing a challenge where I have multiple modules of styled components in a file that I need to import dynamically into another file. I recently discovered the method for importing a module, which requires the following code: const Heading = dynamic( ...

What are the steps to resolve the "undefined cannot read property push" error in Node.js?

While attempting to learn Nodejs, I created a simple app. However, when I run "nodemon index.js" in the command prompt, I encountered the following error: TypeError: Cannot read property 'push' of undefined The app crashed and is now waiting for ...

Customize your Joi message using the .or() method

I'm attempting to personalize a message for the .or() function in Joi, similar to this: https://i.stack.imgur.com/68dKx.png The default message from Joi is as follows: Validation Error: "value" must contain at least one of [optionOne, optionTwo] ...

Unable to use model.find() in post findOneAndUpdate hook for Mongoose

Introduction In Mongoose, I am facing an issue with a post findOneAndUpdate hook where I need to perform a database query. Specifically, when trying to execute a .find() operation on another model, I encounter the following error: Error Description Typ ...

Difficulties encountered when initiating CRA using npm start

Hi everyone! I'm dealing with a frustrating issue; every time I try to run npm start I keep encountering the error message below: events.js:288 throw er; // Unhandled 'error' event ^ Error: spawn cmd ENOENT To resolve this probl ...

Headers error encountered during sending request

When making a request with this method, an error labeled as "[ERR_HTTP_HEADERS_SENT] Cannot set headers after they are sent to the client" occurs. I recently started learning about express and might have made some progress. Can you please help me identif ...

Numerous jQuery pop-up windows are being generated instead of just one as intended

When I load an editing form asynchronously on my web page using jQuery.get and display it within a jQuery dialog, multiple instances of the div that I apply .dialog to are unexpectedly being appended to document.body. Here is the code snippet for loading: ...

How to modify a value in a document within a MongoDB collection

I'm having an issue with updating the 'panel' field in both the cards collection and projects collection. Here is my code snippet: const project = await Project.findOne({"code":currentUser.groupcode}); // this works const ...

How can we ensure that pointer events return the same coordinates as touch events when the viewport is zoomed in?

I attempted to utilize pointer events (such as pointerdown) instead of using a combination of touch events (e.g. touchstart) and mouse events (e.g. mousedown) to determine the input event coordinates. var bodyElement = document.body; bodyElement.addEvent ...

"An error occurred while trying to retrieve memory usage information in Node.js: EN

Is there a way to successfully run the following command in test.js? console.log(process.memoryUsage()) When running node test.js on my localhost, everything runs smoothly. However, when attempting to do the same on my server, I encounter this error: ...

A guide on combining two counters in Vue to create a unified value

Is there a way to track the number of times two buttons are clicked individually as well as together? <div id="app"> <p><button v-on:click="counter1 += 1">Add One More Click</button></p> <p>&l ...