Angular 10: Module Alias Import Not Resolving in VSCode due to Path Mapping Recognition Issue

After updating a project from Angular 8.2 to version 10, I followed the instructions on https://update.angular.io/ and everything seemed fine. However, once I implemented Path Mapping, I started encountering this error everywhere:

Cannot find module '@environments/environment' or its corresponding type declarations.ts(2307)

This error specifically affects @environments and @modules which are declared in the paths. The other modules do not show any errors because they are not being used.

Currently, the project builds correctly using ng build without any errors, but when using ng build --prod, Visual Studio Code (v1.46.1) displays import errors. Here is what I have:

src/tsconfig.json

{
  "files": [],
  "references": [
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path": "./e2e/tsconfig.json"
    }
  ]
}

src/tsconfig.app.json

{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./lw/app",
    "types": []
  },
  "files": ["src/main.ts", "src/polyfills.ts"],
  "include": ["src/**/*.d.ts"],
  "exclude": ["src/test.ts", "src/**/*.spec.ts"]
}

src/tsconfig.base.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "src",
    "outDir": "./dist/lw",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "es2020",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "emitDecoratorMetadata": true,
    "noImplicitAny": false,
    "typeRoots": ["node_modules/@types"],
    "lib": ["es2018", "dom"],
    "paths": {
      "@angular/*": ["./node_modules/@angular/*"],
      ...
    }
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictTemplates": true,
    "strictInjectionParameters": true
  }
}

NOTE: I have tried various baseUrl configurations without success.

Build Result

$ ng build
Generating ES5 bundles for differential loading...
ES5 bundle generation complete.
...

VSCode info

Version: 1.46.1 (user setup)
Commit: cd9ea6488829f560dc949a8b2fb789f3cdc05f5d
Date: 2020-06-17T21:13:20.174Z
Electron: 7.3.1
Chrome: 78.0.3904.130
Node.js: 12.8.1
V8: 7.8.279.23-electron.0
OS: Windows_NT x64 10.0.18363

Angular CLI

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ...
...

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.1000.1
...
typescript                        3.9.6
webpack                           4.43.0

Here is an image showing the organization of my project:

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

In addition, a strange issue arises where certain services, such as CityService, do not show any errors and can be accessed without problems, while other services like ColorService display errors despite having a similar structure.

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

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

Answer №1

I have successfully resolved the issue by implementing the following changes:

  1. To resolve the issue, copy all the code from either tsconfig.base.json or tsconfig.app.json and paste it into the tsconfig.json file. Then, you can remove the tsconfig.base.json or tsconfig.app.json file.

  2. Update the path in the tsconfig.app.json or tsconfig.base.json file to point to the correct location by modifying the extends property as shown below:

     {
     "extends": "../tsconfig.json" 
     ...
     }
    

Here is the code found in the tsconfig.json file:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "downlevelIteration": true,
    "module": "es2020",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2015",
    "strict": false,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ],
    "paths": {
      "@app-models": [
        "src/app/model/index"
      ],     
      "@app-core": [
        "src/app/core/index"
      ],
      "@app-shared": [
        "src/app/shared/index"
      ]
    }
  }
}

A) If ng serve is active, restart it by following these steps:

CTRL + C
ng serve

B) If ng serve is not active, perform the following actions:

Command + Shift + P
Search for "TypeScript: Restart TS Server"
Press enter

Answer №2

We encourage you to update the following:

'environments/environment'

with

'src/environments/environment'

Answer №3

There is a scenario that echoes the current question, although it differs from the original post. I would like to share the question and answer here.

When working with Angular 13, if you decide to rename files that are being imported or if you rename an exported class, there may be instances where the Angular CLI fails to recognize these imports with @features, etc...

After attempting a few solutions without success, I decided to take a different approach. I removed the .angular folder in the root directory, which is a new feature used for caching purposes. Following that, I ran npm start again. Surprisingly, this resolved the issue with the renamed imports.

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

Troubleshooting Problem: Incompatibility with Angular 1 and Angular 2 Hybrid Application causing Display Issue with Components

In my development work, I have created a unique hybrid application that combines Angular 1 and Angular 2 functionalities. This hybrid setup was achieved by following the guidelines provided in two helpful resources: Upgrading from AngularJS and Migrating A ...

Sharing packages within nested scopes

Using @organization-scope/package/sub-package in npm is what I want to achieve. Here is my package.json configuration:- { "name": "@once/ui", ... ... } If I try the following:- { "name": "@once/ui/select-box", ... ... } An error pops up st ...

Using Angular with THREE JS integration in Javascript

I am currently experimenting with Angular and facing a challenge that I can't seem to figure out. The issue I am encountering involves integrating a javascript code, SunLight.js, from the repository https://github.com/antarktikali/threejs-sunlight in ...

The React Quill interface is unable to load due to an undefined window

I recently integrated React Quill into my Next.js project and everything was functioning properly. However, I encountered an issue when attempting to incorporate ImageResize into the editor. Upon adding the line Quill.register('modules/imageResize&ap ...

Is Angular CLI incorrectly flagging circular dependencies for nested Material Dialogs?

My Angular 8 project incorporates a service class that manages the creation of dialog components using Angular Material. These dialogs are based on different component types, and the service class is designed to handle their rendering. Below is a simplifie ...

Implementing TypeScript with styled components using the 'as' prop

I am in the process of developing a design system, and I have created a Button component using React and styled-components. To ensure consistency, I want all my Link components to match the style and receive the same props as the Button. I am leveraging t ...

Loading Angular 4 Material Tabs when a tab is selected

Can lazy loading be implemented with Angular Material Tabs? If not, I am looking for a solution to execute a method when switching tabs. ...

What is the injection token used for a specialized constructor of a generic component?

I created a versatile material autocomplete feature that I plan to utilize for various API data such as countries, people, and positions. All of these datasets have common attributes: id, name. To address this, I defined an interface: export interface Auto ...

The resource in CosmosDB cannot be found

I have successfully stored documents on Cosmos, but I am encountering an issue when trying to retrieve them using the "read" method. this.cosmos = new CosmosClient({ endpoint: '' key: '' }); this.partitionKey = '/id' thi ...

Is it possible for form controls to inherit from another form?

Two key elements make up my structure: The ParentComponent and ChildComponent: parent.component.ts <form #form="ngForm" (ngSubmit)="onSubmit(form)" novalidate> <input type="text" name="firstControl" [(ngModel)]="firstControl" /> ...

Is ts-node necessary for using TypeScript in Node.js?

Having trouble setting up a Node.js application in Visual Studio Code using TypeScript due to issues with importing modules. Initially, I created an index.ts file with the import statement -> import config from './app/config.json'; This resu ...

Identifying the moment when a user deselects an option in mat-autocomplete

I am looking for a way to update other form fields based on the value of an autocomplete selection. To achieve this, I have implemented the optionSelected event handler: <mat-autocomplete (optionSelected)="onOptionSelected($event)"> <mat-opt ...

Leverage properties within the storybook component template

When utilizing a class component in a narrative, it allows you to transmit properties as arguments: const Template: Story<MyComponent> = (args) => ({ props: args, component: MyComponent, }) export const Default = Template.bind({}); export co ...

Transforming ng-bootstrap carousel to utilize div elements instead of images

I am currently utilizing ng-bootstrap and Angular, along with chart.js. I have successfully created two charts that update in real-time with data. My goal is to display these charts within a carousel, allowing users to slide between them. I've been at ...

Navigating with Tabs in Ionic Angular is a Breeze

Here is the routing configuration found in app-routing.module: const routes: Routes = [ { path: 'displayfile/:navitemid', loadChildren: () => import('./pages/file-viewer/file-viewer.module').then( m => m.FileViewerPageMo ...

Guide on creating rsa key pair on the client side with angular2

Is there a way to generate an 'rsa' key-pair on the client-side using angular2? I am looking to create a private/public key pair and store the private key in a database while using the public key on the client side. How can this be achieved? I c ...

Is there a way to retrieve the ReturnType<T> for all methods within a class, even if the ReturnType<T> and its usage appear to be static?

After extensively reviewing the documentation on typescript at https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypet, I have come across two instances of ReturnType<T> mentioned. However, these instances appear to be statically ...

Long wait times for Angular 2 applications to load

My Angular 2 app is experiencing slow loading times, almost 8 seconds. Upon investigation, I discovered that the longest load time is attributed to rxjs. The app makes numerous requests to rxjs/observable, rxjs/add and rxjs/operator. How can I enhance the ...

"Setting up a schema in TypeORM when connecting to an Oracle database: A step-by-step guide

As a newcomer to TypeORM, I'm using Oracle DB with Node.js in the backend. Successfully connecting the database with TypeORM using createConnection(), but struggling to specify the schema during connection creation. One workaround is adding the schem ...

The object literal is restricted to defining existing properties, and 'id' is not a recognized property in the type 'FindOptionsWhere<Teacher>'

I encountered a persistent error within my teachers.service: Object literal may only specify known properties, and 'id' does not exist in type 'FindOptionsWhere | FindOptionsWhere[]'.ts(2353) FindOneOptions.d.ts(23, 5): The expected t ...