Error encountered when attempting to utilize Path Aliases in Angular 11.tsconfig

Currently, I am working on a project using Angular 11 and aiming to utilize short imports like import {smthg} from '@common' instead of

import {smthg} from '../../../common'

However, I keep encountering errors in IDEA:

TS2307: Cannot find module '@common' or its corresponding type declarations.

The same error appears in the console when attempting to compile .ts files (ng serve)

An interesting observation is that adding /index to the import resolves the issue in IDEA but does not eliminate the error in the console

myAngularProject
│   package.json
│   tsconfig.json
│   tsconfig.app.json
│   angular.json    
│
└───src
    │   main.ts
    │   index.html
    |
    └───app
        |  
        └───common
        |
        └───features

Here is an excerpt from tsconfig.json:

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "compileOnSave": false,
  .... (omitted for brevity)
}

This is how tsconfig.app.json looks:

{
  "extends": "./tsconfig.json",
  .... (omitted for brevity)
}

For more details on the IDEA error, you can refer to: https://i.sstatic.net/WAalZ.png

To check the console tsc error, visit: https://i.sstatic.net/CFRNH.png

Information regarding versions being used:

Angular CLI: 11.0.7
... (list of various packages and versions)
typescript                      4.0.5

Answer №1

Interestingly, the angular engine has a feature that allows for creating aliases for paths based on what is defined in the "paths" section of tsconfig.

To ensure access to both subfolders within a module and what is exported from index.ts at the module's top level, the "paths" configuration should be set up like this:

{
  ...
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@common/*": ["app/common/*"],
      "@common": ["app/common/index.ts"]
    }
  ...
  }
}

Answer №2

I encountered a similar issue when attempting to transition a project from Angular 10 to Angular 11. I tried copying the ./src/app folder, but unfortunately, that approach did not yield the desired results...

However, in a fresh project setup, I managed to make path aliasing work by following these steps:

  • Start by updating your Angular CLI:
PS C:\Projects> npm uninstall --g @angular/cli
PS C:\Projects> npm i --g @angular/cli
  • Create a new project and enable strict mode setting to true:
PS C:\Projects> ng new <<name-project>>
PS C:\Projects> cd <<name-project>>
  • After the CLI finishes, make the following modifications to tsconfig.app.json:
/* More details on this file are available at: https://angular.io/config/tsconfig. */
{
    "extends": "./tsconfig.json",
    "compilerOptions": {
        "outDir": "./out-tsc/app",
        "types": [],

        // INSERT BELOW ↓↓↓
        "baseUrl": "./",
        "paths": {
            "@tool/*": [ "src/app/tool/*" ],
            "@models/*": [ "src/app/models/*" ],
            "@services/*": [ "src/app/services/*" ],
            "@components/*": [ "src/app/components/*" ],
            "@interfaces/*": [ "src/app/interfaces/*" ]
        }
        // INSERT ABOVE ↑↑↑
    },
    "files": [
        "src/main.ts",
        "src/polyfills.ts"
    ],
    "include": [
        "src/**/*.d.ts"
    ]
}
  • Similarly, update tsconfig.json with the following configurations:
/* For more information on this file, refer to: https://angular.io/config/tsconfig. */
{
    "compileOnSave": false,
    "compilerOptions": {
        "outDir": "./dist/out-tsc",
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
        "sourceMap": true,
        "declaration": false,
        "downlevelIteration": true,
        "experimentalDecorators": true,
        "moduleResolution": "node",
        "importHelpers": true,
        "target": "es2015",
        "module": "es2020",
        "lib": [
            "es2018",
            "dom"
        ],

        // ADD THIS ↓↓↓
        "baseUrl": "./",
        "paths": {
            "@tool/*": [ "src/app/tool/*" ],
            "@models/*": [ "src/app/models/*" ],
            "@services/*": [ "src/app/services/*" ],
            "@components/*": [ "src/app/components/*" ],
            "@interfaces/*": [ "src/app/interfaces/*" ]
        }
        // ADD THIS ↑↑↑
    },
    "angularCompilerOptions": {
        "enableI18nLegacyMessageIdFormat": false,
        "strictInjectionParameters": true,
        "strictInputAccessModifiers": true,
        "strictTemplates": true
    }
}
  • Finally, adjust tsconfig.spec.json as shown below:
/* Further details on this file available at: https://angular.io/config/tsconfig. */
{
    "extends": "./tsconfig.json",
    "compilerOptions": {
        "outDir": "./out-tsc/spec",
        "types": [
            "jasmine"
        ],
        "baseUrl": "./",
        "paths": {
            "@tool/*": [ "src/app/tool/*" ],
            "@models/*": [ "src/app/models/*" ],
            "@services/*": [ "src/app/services/*" ],
            "@components/*": [ "src/app/components/*" ],
            "@interfaces/*": [ "src/app/interfaces/*" ]
        }
    },
    "files"quot;: [
        "src/test.ts",
        "src/polyfills.ts"
    ],
    "include": [
        "src/**/*.spec.ts",
        "src/**/*.d.ts"
    ]
}

Answer №3

For successful implementation in Angular version 13, ensure to include a dot (.) in every path value as shown below:

"baseUrl": "./",
"paths": {
      "@app/*": [
        "./src/app/*"
      ],
      "@env/*": [
        "./src/environments/*"
      ]
    }

Answer №4

It is important to remember that restarting your code editor can often solve issues related to linters.

When faced with a similar problem, I discovered that my configurations were correct but the linter was not recognizing changes until I restarted my IDE. This lack of experience led me to try multiple solutions before finding this simple fix.

Answer №5

Path aliases are no longer supported in the latest versions

However, there is a workaround to directly import files relative to the src folder

Simply navigate to your tsconfig.json file and add baseUrl with the value of "."

"compilerOptions": {
    "baseUrl":".",
    ...

This allows you to import items directly from the src directory

import Myfile from "src/myfile.js"

I have successfully implemented this method!

Answer №6

My issue was related to path aliasing, which appeared to be functioning correctly, however upon closer inspection I discovered that a .ts file was missing in the designated folder. This resulted in the types not being recognized and led to the following error message: "Cannot find module @app or its corresponding type declarations"

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

Unable to narrow down the truthiness within nested functions: TypeScript issue

When analyzing the code in the shared playground (Playground Link), the compiler is showing an error indicating that Object is possibly 'null'. Could there be any scenario where the refresh function could be called, leading to a situation where ...

JSX is restricted in files using the '.tsx' extension according to eslint rules (react/jsx-filename-extension)

When working in a .tsx file, why does eslint flag the following issue: The use of JSX is not permitted in files with the extension '.tsx' (eslint react/jsx-filename-extension) What steps can I take to adjust the eslint configuration and addres ...

WebSocket establishing fresh connection every passing moment

My Angular 5 application uses a socket.io-client to connect to a websocket server hosted on the Google Cloud Platform. However, instead of opening just one connection, I noticed that multiple connections are being created in the browser, with a new conne ...

Navigating through nested routes in Angular 5

I recently started learning about Angular, and I could really use some guidance on routing. Here is my current setup. app.component.html <router-outlet name="nav"></router-outlet> <router-outlet name="left-sidebar"></router-outlet> ...

Leverage jsencrypt in Ionic 3

Struggling to hash passwords for login on my Ionic 3 app, I attempted using jsencrypt following a tutorial but encountered issues as I couldn't grasp how it works... Here's what I tried : npm install --save jsencrypt import { Component } from ...

The Standalone Component does not appear for debugging in webpack:source when utilizing an incompatible version of Node

I have developed two components: However, after running ng serve, I am only able to see one component in the source of the Chrome browser: How can I troubleshoot this standalone component? My breakpoints are not being hit in VS Code with the following co ...

An issue occurred in the modal window following the relocation of project files

I encountered an issue with the modal in my Nativescript project after rearranging a few project files, including the modal. I updated the imports and deleted any compiled JavaScript files to ensure that my project could recompile correctly. Although I&ap ...

Implementing the 'colSpan' attribute in ReactJS

I encountered an error saying "Type string is not assignable to type number" when attempting to include the colSpan="2" attribute in the ReactJS TypeScript code provided below. Any suggestions on how to resolve this issue? class ProductCategoryRow exten ...

The map component does not render when the agm-map is placed within the component

Objective I am attempting to encapsulate an <agm-map> within my custom <app-map> component, but it is not appearing in the HTML output. The agm (angular google maps) library is properly configured and the map displays correctly when the <a ...

Validation scheme for the <speak> element

When using validators in an angular formarray for input fields, I encountered a challenge with the regex to check the <speak> tag. The content provided was considered valid. An error is thrown based on the specified pattern. However, it should als ...

Ways to leverage a single observable to modify a second one

I'm facing an issue while trying to utilize an observable favourites$ in order to construct another array of the same type. I am anticipating that the favourites$ observable will be filled with an array of type University, and then I can update a clas ...

When attempting to navigate to a sub-route, I am encountering the error message: "Unable to find a matching route" in Angular 6

The initial code is functional, but not the best practice. const FooProcessingRoutes: Routes = [{ path: '', pathMatch: 'full', redirectTo: '/foo-processing/list', }, { path: 'list', component: FooListCompo ...

Converting a string to the Date class type in Angular 4: A comprehensive guide

Within my .ts file, I have a string that looks like this: const date = "5/03/2018"; I am looking to convert it into the default date format returned by Angular's Date class: Tue Apr 03 2018 20:20:12 GMT+0530 (India Standard Time) I attempted to do ...

Restricting the data type of a parameter in a TypeScript function based on another parameter's value

interface INavigation { children: string[]; initial: string; } function navigation({ children, initial }: INavigation) { return null } I'm currently working on a function similar to the one above. My goal is to find a way to restrict the initi ...

Tips for preventing unnecessary dependencies from being installed in an Angular 10 application

I've been working on a project using Angular 10. Surprisingly, my package.json doesn't mention anything about @babel. However, every time I run npm install, an error occurs: npm ERR! 404 Not Found - GET http://private_repo/repository/npm-all/@bab ...

Eliminate repeat entries in MongoDB database

Within our MongoDB collection, we have identified duplicate revisions pertaining to the same transaction. Our goal is to clean up this collection by retaining only the most recent revision for each transaction. I have devised a script that successfully re ...

Passing variables in Ionic's <a href> to open an external page: A step-by-step guide

I am trying to implement a feature in Ionic where I need to call a PHP page. In the home.html file, there is a URL being called like this - <a target="_blank" href="https://www.example.com?">pdf</a> The challenge now is to add a variable from ...

When running the ng test command, the error "TypeError: The 'compilation' argument must be an instance of Compilation" is generated, but the ng build command functions correctly

When attempting to execute unit tests using 'ng test libraryprojectname', I encounter the following error. Interestingly, ng build functions properly without any issues. The project in question is a workspace that includes an Angular library. Any ...

What could be preventing me from setting a boolean variable within an Observable?

After retrieving data from the Service, I am attempting to hide a specific div element. Below is the HTML code: <progressbar *ngIf="isLoadingBootStockData" [value]="100" type="default"> </progressba ...

Signal a return type error when the provided element label does not correspond with an existing entity

I am working on a component that accepts three props: children (React elements), index, and label. The goal is for the component to return the child element at a specific index when index is passed, and to return the element with a specific label when la ...