Having trouble with Angular 5 tsconfig baseURL not functioning properly?

This may appear straightforward, but I am facing difficulties with it

My Angular 5 application consists of three files located as follows:

app_directory/tsconfig.json
app_directory/src/app/services/my-service.service.ts
app_directory/src/app/main/sub1/sub2/my-component.component.ts

In the my-component.component.ts file, I can import my-service successfully using the following line:

import { MyServiceService } from '../../../services/my-service.service.ts'

Although this works fine, it can be tedious to include the relative path every time I need to import this service. I came across a post on SO that discusses this issue: How to avoid imports with very long relative paths in Angular 2?

I decided to implement the same approach by modifying my tsconfig.json as shown below:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./src/app/",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

I also adjusted my import statement to the following:

import { MyServiceService } from 'services/my-service.service.ts'

Unfortunately, this change did not yield the desired result. I played around with various values for baseUrl without success:

.
./
./app
./src
./app/
./src/
src/app
src/app/

It appears that the tsconfig baseUrl setting is having no impact whatsoever. What could I be overlooking here?

Answer №1

After much troubleshooting, I finally cracked the code... Turns out, my tsconfig file was completely ineffective because it wasn't even being utilized.

Here's how I unraveled the mystery:

The site was being served using the following command:

npm start

I knew that this command referenced my package.json and executed the script defined under {"scripts":{"start" ...}. In my case, it was:

ng serve --sourcemap --extract-css --host 0.0.0.0 --proxy-config proxy.config.json

It's worth mentioning that I inherited this codebase and had limited knowledge about its initial setup. Nevertheless, I also discovered that whenever ng serve is executed, it looks for a file named .angular-cli.json. Here's an excerpt from my angular.cli.json (the relevant part):


{
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.scss"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts",
        "up-gui-1": "environments/environment.up-gui-1.ts"
      }
    }
  ]
}

That line stating "tsconfig":"tsconfig.app.json" stood out to me.

Indeed, I did not have a file named tsconfig.app.json in the root directory. However, upon further investigation, I found one level down inside the src directory. I edited that file to include:

"baseUrl": ".",
"paths": {
  "@services/*": ["./app/services/*"]
},

Subsequently, I updated my import statement to:

import { MyServiceService } from '@services/my-service.service';

Voila! The issue was resolved.

Answer №2

One key distinction I notice between your approach and the previous answer is that you are neglecting to utilize the paths configuration in your angular-cli.json file, alongside the baseUrl setting. It seems like they are leveraging this feature to enable mapping a base path, along with corresponding subdirectories, to a designated path on the file system. To achieve the desired functionality in your code, follow these steps:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./src/app/",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ],
    "paths": {
      "services/*": [
        "services/*"
      ],
      "components/*": [
        "main/sub1/sub2/*",
        "main/sub3/sub4/*"
      ]
    }
  }
}

// Subsequently, you can import modules as shown below:

import { MyServiceService } from 'services/my-service.service.ts'
import { MyComponentComponent } from 'components/my-component.component.ts'

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

Getting the button element in Angular when submitting a form

My web page contains multiple forms, each with a set of buttons. I want to incorporate a loading spinner on buttons after they are clicked. When using a regular click event, I am able to pass the button element: HTML <button #cancelButton class="butto ...

What is the proper way to manage the refresh token on the client's end within a JWT system?

Curious about what exactly occurs on the client side when the refresh token expires. Is the user directed to a login page and remains logged in, or does the client side log them out automatically? My understanding is that the refresh token is saved in an ...

Transforming an array of strings into an array: a guide

An API call is returning an object with the following structure: data = { ... filter: "[1,2,3]" ... } I need to convert the string of array into an actual array of numbers, like [1,2,3]. Thank you! ...

Exploring the integration of multiple HTTP requests in Angular with the power of RxJS

Is there a way to make multiple HTTP calls simultaneously in an Angular service and then combine the responses into one object using RxJS? import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; im ...

Angular 2 fails to identify any modifications

Within my template, the links are set to change based on the value of the 'userId' variable. <nav> <div class="nav-wrapper"> <a href="#" class="brand-logo"><img src="../../public/images/logo.png" alt="" /></a> ...

Steps for accessing the camera within a custom Ionic app

Currently, I am working on a unique custom application built using Ionic and Typescript. I have encountered an issue with opening the camera to capture a picture. While my app successfully opens the native camera for capturing photos, it unfortunately tak ...

Resolve routing problems with lazy loading in Angular7

I have been working on implementing lazy loading in my Angular project. However, I am encountering the same error even after following the suggested solution. Lazy loading error on StackOverflow I have exported the components from the project module and im ...

Custom options titled MUI Palette - The property 'primary' is not found in the 'TypeBackground' type

I am currently working on expanding the MUI palette to include my own custom properties. Here is the code I have been using: declare module '@mui/material/styles' { interface Palette { border: Palette['primary'] background: Pa ...

What could be the reason for the discrepancy between my get_token() function and the value obtained from request.META.get("CSRF_COOKIE")?

Can anyone shed light on why I'm facing this particular issue? I am currently exploring the integration of Angular 17 as a Frontend with Django as a Backend. While validating a form, I encountered an issue where the token obtained from Django does no ...

What is the best way to establish communication between the browser and an express.js server while utilizing angular ssr?

I've encountered a server-side rendering (SSR) issue that does not seem to be addressed in either the Angular documentation or the new Angular developer documentation. My inquiry pertains to transferring data from the browser to the server, as oppose ...

Struggling to retrieve data with arrow function in Vue

I'm currently learning Vue and facing an issue with fetching data from an API to my component. I have a service class that successfully retrieves data from the API, as the API itself is working fine. Here's the code snippet: import IReview from & ...

Issue encountered: Compilation error occurred following the update from Angular 11 to Angular 15, stemming from the module build failure within the sass-loader directory

I recently attempted to update angular from version 11 to 15, but encountered an error as shown in the screenshot below ./src/assets/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: expected "(". ...

Unexpected TypeScript issue: Unable to access the 'flags' property of an undefined entity

Upon creating a new project and running the serve command, I encountered the following error: ERROR in TypeError: Cannot read property 'flags' of undefined Node version: 12.14 NPM version: 6.13 Contents of package.json: { "name": "angular-t ...

Utilizing const as the iteration variable in a for loop

I've grasped the concept of using var and let in a for loop in typescript/javascript, but can someone shed light on how and why a const variable as a loop variable behaves? for (const i = 0; i < 5; i++) { setTimeout(function() { console.log( ...

Encountering a discord bot malfunction while on my Ubuntu server

My discord bot runs smoothly on my Windows 10 setup, but when deployed to the server running Ubuntu Server 20, it encounters a specific error. The issue arises when trying to handle incoming chat messages from the server. While I can read and respond to m ...

Error in TypeScript: Circular reference in type alias 'Argument' in node_modules/classnames/index.d.ts at line 13:13

Need help troubleshooting an error while building my project. Can't find much information online to resolve this issue. I am using typescript 4.2.4 I can't locate the classnames/index.d.ts file in any directory, so I'm unable to make any ch ...

Is it advisable to blend Angular Material with Bootstrap?

I'm brand new to Angular Material and it seems to have its own intricate API. Coming from using Bootstrap, I'm accustomed to utilizing its grid system with classes like row, containers, cols, etc. I'm curious if it's considered a good o ...

A guide on leveraging Jest and Typescript to mock a static field within a class

While working with Typescript and a third-party library, I encountered an issue trying to write unit tests that mock out the library. Here's an example scenario: // Library.ts // Simulating a third party library export class Library { static code ...

Discovering a user's location with Angular and seamlessly loading components accordingly

How can I delay the loading of a component until the user's location is determined? The project involves a map and an information panel that rely on latitude and longitude coordinates. I attempted to use a Leaflet map and created a resolver, but it do ...

Stringified HTML code showcased

When working with Angular, I have encountered an issue where I am calling a function inside an .html file that returns a string containing a table element. My goal is to convert this string into HTML code. I attempted to use [innerHtml]: <p [innerHtml ...