How to set up imports path aliases for (Angular)

aamhimel

Abdullah Al-Mamun

Posted on May 19, 2024

How to set up imports path aliases for (Angular)

Angular components name becomes unreadable also non maintainable for larger project. Usually we use relative paths to import components like this ("../../../something"), which is not suitable for project that has many nested routes.

import { JobInformationService } from '../../../services/job-information.service';
import { ControlBarComponent } from '../../components/control-bar/control-bar.component';

Enter fullscreen mode Exit fullscreen mode

We can solve this problem by defining path aliases, we can configure this in tsconfig.json file in the root directory.

In the compilerOptions section we can add two things
add this line:

 "baseUrl": "./src",
Enter fullscreen mode Exit fullscreen mode

then also add these, here choose the path and name based on your projects requirement. You can add as many as you want.

"paths": {
      "@components/*" : ["app/components/*"],
      "@pages/*" : ["app/pages/*"],
    }
Enter fullscreen mode Exit fullscreen mode

Add this to your tsconfig.json file

  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@components/*" : ["app/components/*"],
      "@pages/*" : ["app/pages/*"],
    }
  },
Enter fullscreen mode Exit fullscreen mode

Now you can import your components, services, etc. directly using @definedname , for example you can now use like this

import { JobInformationService } from '@services/job-information.service';
import { ControlBarComponent } from '@components/control-bar/control-bar.component';

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
aamhimel
Abdullah Al-Mamun

Posted on May 19, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related