The autoimport feature in VScode should consistently use absolute paths, unless the file being imported is located in the same

Objective: I want VScode to automatically import my dependencies using absolute paths, unless the file is located in the same directory.

For example: Let's say we have ComponentA and ComponentB in the same directory, but a service in a different directory. In that case, I would like the imports to look like this (angular code):

import { ComponentB } from "./ComponentB"
import { MyService } from "src/app/services/MyService"

@Component({/*...*/})
export class ComponentA {}

Based on the default VScode settings options, it seems that this specific scenario is not supported:

"relative" to the file location.
"non-relative" based on the baseUrl configured in your jsconfig.json / tsconfig.json.
"auto" to infer the shortest path type.

Is there a solution that I am missing? Are there any VScode extensions available to address this issue?

Answer №1

This informative resource focuses on the concept of a Base URL - baseUrl.

It's essential to exercise caution when making changes to this, as altering the path could result in numerous errors.

To implement this, add the following line to the tsconfig.json.

{
   ...
  "compilerOptions": {
    "baseUrl": "./",   <-- Add baseUrl
   ....
  },
  "angularCompilerOptions": {
    ...
  }
}

The directory structure is outlined as follows:

└───src
    └───app
        ├───all-service
        └───pages
            ├───comp-a
            └───comp-b

Initially, the import paths looked like this:

import { Component } from '@angular/core';
import { SmapleService } from '../../all-service/smaple.service';
import { MyServiceService } from '../../my-service.service';
import { CompBComponent } from '../comp-b/comp-b.component';

@Component({...})
export class CompAComponent {
   compBComponent: CompBComponent = new CompBComponent();
   service: MyServiceService = new MyServiceService();
   service2: SmapleService = new SmapleService();
}

Upon updating the path:

import { Component } from '@angular/core';
import { CompBComponent } from '../comp-b/comp-b.component';
import { SmapleService } from 'src/app/all-service/smaple.service';
import { MyServiceService } from 'src/app/my-service.service';

@Component({...})
export class CompAComponent {
   compBComponent: CompBComponent = new CompBComponent();
   service: MyServiceService = new MyServiceService();
   service2: SmapleService = new SmapleService();
}

Update: It is advisable to create a Barrel for the service within the folder.

└───src
    └───app
        ├───all-service
        |      └───index.ts
        └───pages
            ├───comp-a
            └───comp-b
// index.ts
export * from './smaple.service';

Lastly,

import { Component } from '@angular/core';
import { SmapleService } from 'src/app/all-service';            // <--Barrel
import { MyServiceService } from 'src/app/my-service.service';  // <--without Barrel
import { CompBComponent } from '../comp-b/comp-b.component';

@Component({
  selector: 'app-comp-a',
  standalone: true,
  imports: [],
  templateUrl: './comp-a.component.html',
  styleUrl: './comp-a.component.scss'
})
export class CompAComponent {

   compBComponent: CompBComponent = new CompBComponent();
   service: MyServiceService = new MyServiceService();
   service2: SmapleService = new SmapleService();
}

The recommendation is to utilize the TypeScript Barrel Generator extension. Additionally, a Barrel is beneficial for modules containing multiple components.

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

Showing elements from an array after adding new items with Ionic and Angular 2 on click

Struggling to update an array using the push method and showcase it in the view? Frustrated that the new value from a text box isn't displaying on the view as expected? If you're puzzled by why all you see is an empty row with no value from the t ...

Obtain access to the child canvas element within the parent component

I'm currently working on an app that allows users to sign with a digital pointer. As part of the project, I have integrated react-canvas-signature. My next task is to capture the signature from the canvas and display it in a popup. According to thei ...

TypeScript interface designed to capture objects containing a flexible number of values

In my possession is an object that looks like the following: { "0001": "a", "0002": "b", "0003": "c", ... } Is it possible for me to create a TypeScript interface that accurately represents this type? ...

Using a Typescript-specific type within a switch case statement

I'm currently working on a function that, when given an enum value, should return a specific type. I am facing an issue where Typescript does not seem to recognize the properties inside switch and if statements. interface X { x: string; } interface ...

Conceal a designated column within a material angular data table based on the condition of a variable

In the morning, I have a question about working with data tables and API consumption. I need to hide a specific column in the table based on a variable value obtained during authentication. Can you suggest a method to achieve this? Here is a snippet of my ...

Creating dynamic HTML content for printing tasks with the use of variables in Angular6

After running this code, I noticed that instead of values, I am receiving the object names. export class PrescriberComponent implements OnInit { constructor() { } people = [ {id: 1, forename: 'John', surname: 'Doe'}, {id: 2, f ...

Can I exclusively utilize named exports in a NextJS project?

Heads up: This is not a repeat of the issue raised on The default export is not a React Component in page: "/" NextJS I'm specifically seeking help with named exports! I am aware that I could switch to using default exports. In my NextJS ap ...

Exploring the nuances of checking lists in TypeScript

In the following list: empList = ['one','two','finish','one','three'] I am required to evaluate conditions based on empList: Condition 1: If 'two' appears before 'finish', set this ...

rxjs - straightforward issue with initiating observables

I'm currently tackling an assignment that involves setting up a basic form with input fields for 'From', 'To', and 'Duration' using rxjs. While it might be easier to just utilize getter / setters, I'm determined to ...

Tips for extracting elements from an HTML document using Angular

I seem to be facing a small issue - I am trying to develop a form using Angular. Below is my HTML: <form [formGroup]="requeteForm" (ngSubmit)="ajouter()" *ngIf=" tables!= null"> <div class="form-group&quo ...

Make the switch from TypeScript namespaces to ES2015 modules

After making adjustments to my TypeScript configuration, I am now encountering errors related to the no-namespace rule. Here is how my current setup involving namespaces looks like: Exporting classes within a namespace: namespace MyNamespace { export ...

"PrimeNG Dropdown: The 'Showclear' option reveals the clear icon right from

In my Angular 7 application, I've been utilizing PrimeNG's Dropdown component which has been performing well. Typically, I set the showClear property to true to display a small "x" button on the right side of the dropdown control. Clicking on thi ...

Create a compilation of categories/interfaces based on a mapping

Imagine you have the following object: const ROUTES = { PAGE_NO_PARAMS: '/hello/page/two', PAGE_R: '/about/:id', PAGE_Z: '/page/page/:param/:id', PAGE_N: '/who/:x/:y/:z/page', } as const Can we create a set ...

Never display mat-select panel when closed

In my current scenario, I am using the following template structure: <mat-select #select> <mat-option *ngFor="let option of optionsData"> {{ select.panelOpen ? option.viewValue : option.value }} </mat-option&g ...

The error message "TranslateService not found" seems to be linked to the npm installation process

Encountering an issue with my Angular+Webpack+JHipster+yarn project where a particular error keeps reappearing despite deleting `node_modules` and running 'npm install`. The error seems to be related to the TranslateService provided by a library, not ...

Reactivity in Angular Autocomplete with API Integration

I went through all the tutorials on Angular Autocomplete using API to follow the steps. I implemented valueChanges to monitor the form control, used switchMap to send a new request with each keyword change, and then displayed the data in the autocomplete d ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

Issue with Ionic 4 button not triggering event when created using Jquery

Utilizing Ionic 4 in my current project, I have integrated it with Jquery. On the HTML page, a button is created using the following code: <ion-button (click)="event1()">EVENT1 </ion-button> In the .ts file for the page, a function is impleme ...

Implementing ETag in Angular 2

Implementing the odata standard which utilizes ETag has presented a challenge for me, particularly with PATCH requests. Each PATCH request requires sending the ETag in the header as If-None-Match. A HTTP status of 200 indicates that the change was successf ...

Creating a TypeScript client using NSwag with named properties: A step-by-step guide

Our TypeScript client is created from a swagger interface using NSwag. The resulting client code typically looks like this: client.EndPointFoo(arg1, arg2, arg3, ...) However, we encounter issues when NSwag changes the order of arguments in response to mo ...