How to Use Absolute Paths For Module Imports in Angular

    Dec 01, 2020       by Pankaj Kumar
how-to-use-absolute-paths-for-module-imports-in-angular.jpg

Photo by George Bakos on Unsplash

Many of us feel confused while we need to import module which is not in the same folder or near by. To make this task easier, We can make the path absolute so that we do not need to worry about path.

From long time, I was feeling need of a solution which could resolve the problem of importing module available in nested folder. Recently I found a way to resolve it which I am going to share with you, It's very easy and quick.

Let's say we have to use the service class inside any component which is available in nexted folder then the import statement will look like below:

import { ReferralService } from '../../../../../_services/referral.service';

 

Such imports are too long, hard to maintain and very annoying in bigger projects. So now I follow the latest approach to perform the same task. Now let's move to the solution part.

open your tsconfig.json file(in some version of angular you can find tsconfig.base.json also, open this instead). Inside compiler option make sure you have below settings:

"compilerOptions": {

  ...

  "baseUrl": "./",

  ...

 

}

 

If the baseUrl is same then now you can define your own absoulte path as many as you want. In our case, since we are trying to change the path for the environment then add the below line into compilerOption inside tsconfig.json file.

"compilerOptions": {

  ...

  "baseUrl": "./",

  "paths":{

   "@services/*": ["src/app/_services/*"],

  }

  ...

 

}

 

Now from any part of the application why not it's at availabe the the most nested folder, any service class can be imported using below statement.

import { ReferralService } from '@services/referral.service';

 

In the above line we have mapped the './src/app/_services' with @services, Here @ symbol is not mendatory. And the best thing is that, We can define any number of absolute path as per the requirement in our application.

 

Conclusion

Using absolute path in the angular app makes our code clean, easy to read, and easy to maintain.

I hope this article helped you to improve your coding in Angular. You can also find other demos/articles at Angular Sample Projects here to start working on enterprise-level applications.

Let me know your thoughts over email pankaj.itdeveloper@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thanks!


Find other similar Articles here: