Having trouble with VSCode/tsconfig path configurations, as the files are being fetched but still receiving a "Module not found" error in the editor

Since I began working on this project, I've been encountering a peculiar issue. When importing modules and files in my Angular components/classes using import, I face an error in VSCode when the paths use the base path symbol @. Strangely enough, despite the warning, I can compile and run the application without any problems as all imports are successfully pulled in.

This issue has been lingering for some time now, but it becomes particularly inconvenient when I attempt to navigate to the definition of an object from one of the imported modules in VSC and it fails to locate the file.

All members of my team are utilizing the same code base (and tsconfig file) in VSCode without experiencing this hiccup, indicating that it may not be a problem with the tsconfig file or codebase setup itself, but rather something specific to my own VSCode environment. Despite scouring through StackOverflow and other resources for solutions, I have yet to find a resolution. Any assistance would be greatly appreciated.

Example of import at the top of an Angular ts file:

import { SigningAction } from '@middlemass.signing/dto/signing-action';

Upon hovering over any import with a path shortcut prefix, here is the warning message I receive:

Cannot find module '@middlemass.signing/dto/signing-action' or its corresponding type declarations.

tsconfig.json:

{
    "compileOnSave": false,
    "compilerOptions": {
      "outDir": "./dist/out-tsc",
      "sourceMap": true,
      "declaration": false,
      "moduleResolution": "node",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "removeComments": false,
      "suppressImplicitAnyIndexErrors": true,
      "target": "es5",
      "resolveJsonModule": true,
      "allowSyntheticDefaultImports": true,
      "esModuleInterop": true,
      "typeRoots": [
        "node_modules/@types"
      ],
      "lib": [
        "es2017",
        "dom"
      ],
      "module": "es2015",
      "baseUrl": "./",
      "paths": {
        "@middlemass.sending/*": [
          "projects/middlemass-sending/src/*"
        ],
        "@middlemass.sending/shared/*": [
          "projects/middlemass-sending/src/shared/*"
        ],
        "@middlemass.sending/utils/*": [
          "projects/middlemass-sending/src/shared/utils*"
        ],
        "@middlemass.sending/services/*": [
          "projects/middlemass-sending/src/services/*"
        ],
        "@middlemass.sending/dto/*": [
          "projects/middlemass-sending/src/dto/*"
        ],
        "@middlemass.sending/env/*": [
          "projects/middlemass-sending/src/environments/*"
        ],
        "@middlemass.sending/styles/*": [
          "projects/middlemass-sending/src/scss/*"
        ],
        "@middlemass.sending/locale/*": [
          "projects/middlemass-sending/locale/*"
        ],
        "@middlemass.signing/locale/*": [
          "projects/middlemass-signing/locale/*"
        ],
        "@middlemass.signing/dto/*": [
          "projects/middlemass-signing/src/app/core/dto/*"
        ],
        "@middlemass.signing/services/*": [
          "projects/middlemass-signing/src/app/core/services/*"
        ],
        "@middlemass.signing/shared/*": [
          "projects/middlemass-signing/src/app/shared/*"
        ],
        "@middlemass.signing": [
          "projects/middlemass-signing/src"
        ],
        "@middlemass.signing/*": [
          "projects/middlemass-signing/src/*"
        ],
        "@middlemass.common": [
          "projects/middlemass-common/src"
        ],
        "@middlemass.common/*": [
          "projects/middlemass-common/src/*"
        ]
      }
    },
    "angularCompilerOptions": {
      "fullTemplateTypeCheck": true,
      "strictInjectionParameters": true,
      "preserveWhitespaces": false
    }
  }

Answer №1

After some investigation, it turns out that the issue I was facing wasn't related to VSCode or tsconfig at all. Surprisingly, I realized that our code base actually consists of three distinct projects housed within one main directory. Typically, my team and I focus on one project at a time, opening its specific directory for development work. Despite each project having its own tsconfig file inheriting from the root directory, not having the root directory opened in VSCode was causing the problem.

The structure of the code base is as follows:

Projects Folder (root with the "master" tsconfig)
   --Project I (with its own tsconfig extending the root tsconfig)
   --Project II (with its own tsconfig extending the root tsconfig)
   --Project III (with its own tsconfig extending the root tsconfig)

All I needed to do was open the Projects folder in VSCode to enable the base path shortcuts. Initially, I mistakenly thought that by opening the individual project folders with their respective tsconfig files would suffice, but that's not how it worked. Having the root folder open, which contains the master tsconfig file, was crucial.

One downside to this approach is that searching for files or code within one project may yield results from the other projects. However, you can customize your VSC workspace settings to prevent this:

"search.exclude": {
    "**/node_modules": true,
    "**/bower_components": true,
    "**/*.code-search": true,
    "**/projects/project1": true,
    "**/projects/project2": false,
    "**/projects/project3": false
  }

By configuring these settings, when working in project1, you will only see search results relevant to project1. You can adapt this pattern accordingly based on the project you are currently focused on.

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

The toggle-button's group property does not function properly when paired with ngIf

The group property is not functioning as expected when using ngIf in the toggle-group. Here is the code snippet: <mat-button-toggle-group *ngIf="query.noOfQuestions == 05" (change)="toggleChangeQuestion($event)" name="selectQue ...

Working with Typescript and JSX in React for event handling

I'm currently facing an issue with updating the state in a React component I'm developing using TypeScript (React with Addons 0.13.3, Typescript 1.6.0-dev.20150804, definition file from ). /// <reference path="react/react-addons.d.ts" /> i ...

Broadening Cypress.config by incorporating custom attributes using Typescript

I'm attempting to customize my Cypress configuration by including a new property using the following method: Cypress.Commands.overwrite('getUser', (originalFn: any) => { const overwriteOptions = { accountPath: `accounts/${opti ...

Break down the key:value objects into individual arrays

I'm currently working on an ionic project that involves handling an incoming array composed of key:value objects such as the one shown in the image below: https://i.stack.imgur.com/qrZiM.png My question is, can these values be separated into three d ...

Tips for determining the minimum value within an array of objects across multiple keys using a single function

I am currently tasked with the challenge of determining the minimum value from an array of objects that contain multiple keys. My ultimate goal is to identify the minimum value among all keys or specific keys within the objects. For instance var users = ...

Error: Trying to access 'MaterialModule' before it has been initialized results in an uncaught ReferenceError

I have been working on a form for a personal project and attempted to implement a phone number input using this example: . However, after trying to integrate it into my project, I encountered an error. Even after removing the phone number input code, the e ...

Encountering a runtime issue with socket.io when using typescript that has been bundled by

Recently, I attempted to implement web sockets using socket.io in a Node server written in TypeScript with ExpressJS and bundled with Webpack. The server code is structured as follows: import * as Express from "express"; import * as SocketIO from "socket ...

What is the most effective method to create a versatile function in Angular that can modify the values of numerous ngModel bindings simultaneously?

After working with Angular for a few weeks, I came across a problem that has me stumped. On a page, I have a list of about 100 button inputs, each representing a different value in my database. I've linked these inputs to models as shown in this snipp ...

The functionality of Angular 4's ngStyle sum operates as a string instead of a number

<div class="scroll-element-content" [ngStyle]="{'width.px': (this.width + this.trackWidth)}"> With this.width set to 400 and this.trackWidth set to 8: The combined width of .scroll-element-content will be 4008 (since the sum is treated as ...

Angular component testing encountering undefined NgZone

I am facing a challenge while testing for bad input values in an Angular Date Range picker component that I am developing. In my ngOnInit() function, I include a check for minimum and maximum date values. However, when attempting to write a test case for ...

What are some ways to customize the functionality of the data table filter in Angular Material?

Attempting to use the filter feature in Angular Material Data Table: When searching for "MATCHED", both "MATCHED" and "UNMATCHED" are displayed in the status column of the table. It seems this is due to the data object being reduced and concatenated befo ...

When using Angular with mdbootstrap, the mdb-tabs directive will move to the end if the ngIf condition is true

Currently facing a challenge with a significant amount of code here. It is referenced as follows: "ng-uikit-pro-standard": "file:ng-uikit-pro-standard-8.3.0.tgz", I am attempting to display a tab between 1 and 3 if a certain condition ...

I possess a JSON array object and need to identify and extract the array objects that contain a specific child node

const jsonArray = { "squadName": "Super hero squad", "homeTown": "Metro City", "formed": 2016, "secretBase": "Super tower", "active": true, "members": [ { "name": "Molecule Man", "age": 29, "secretIdent ...

Angular - Issue with Function Observable<number> in Development

Currently, I'm working on writing TypeScript code for a component. Within this TypeScript class, I have created a function that is meant to return a number representing the length of an array. My goal is to have this function work like an Observable. ...

Struggling to incorporate method decorators to handle http errors in Angular?

My goal is to implement error handling for all http requests using custom decorators. Here's my current code snippet: createRecord(data: data) { return this.httpClient.post(`${this.apiURL}/record/`, data); } I am looking to refactor thes ...

Implementing error wrapper in typescript to handle failing promises with n retries

I have a wrapper function that calls an async function: function fetchAPI(arg1: number, arg2: number, arg3: string) { return new Promise((resolve, reject) => { try { myFetchFunction(arg1, arg2, arg3).then((r: any) => { if (!r) { ...

Trigger a class method in an event using Angular with Typescript

I am completely new to TypeScript and Angular, and I am attempting to create a basic drawing component on a canvas. However, I have reached a point where I feel lost and confused about my code. The concept of "this" in TypeScript has been a major stumbling ...

Utilizing template logic that draws from a fusion of two distinct texts

Looking to display two different texts depending on a boolean value. Here is what I attempted: <div name="health-plans" *ngIf="!flagon"> Test<br />data </div> <div name="health-plans&quo ...

Error: The file type you are trying to upload is not supported

my document-upload.service.ts private uploadFile(file: File) { let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new HttpHeaders({'Content-Type': 'multip ...

What is the best way to locate an item within a Redux array when working with TypeScript?

Below is the content of my slice.ts file. interface iItem { Category: string; Id: string; } interface iDataState { Items: Array<iItem>; } const initialState: iDataState = { Items: [], }; reducers: { updateItem: (state, action: PayloadAc ...