Import via Absolute Paths in Angular
Are you tired of long and unreadable relative imports in your Angular apps? I know I was! It turns out there’s a really quick and simple solution to moving from relative imports and to absolute imports.
The Solution
Open your tsconfig.json
file (if you have a tsconfig.base.json
file, which is usually found in Angular 9 or 10 and lower projects, open that file instead).
In the compiler options property, make sure you have your baseUrl
set to ./
.
{
...
"compilerOptions": {
"baseUrl": "./",
...
},
...
}
Lastly, add the absolute path aliases you want to map to various folders in the paths property. For example, if you want to absolute import your environment files, you could define it like so:
{
...
"compilerOptions": {
"baseUrl": "./",
...
},
"paths": {
"@environments/*": ["./src/environments/*"]
},
...
}
The above definition says that you want the absolute path to your environment folder to be @environments
and map to the ./src/environments/*
folder location. The @
is not required, however I like to use it to indicate an absolute import. The import would look like this: import { environment } from ‘@environments/environment’;
.
Another example could be an absolute import of a shared folder that could contain globally shared services, components, validators, etc. You could define it like so:
{
...
"compilerOptions": {
"baseUrl": "./",
...
},
"paths": {
"@environments/*": ["./src/environments/*"],
"@shared/*": "["./src/app/shared/*"]
},
...
}
The above definition says that you want the absolute path to your shared folder to be @shared
and map to the ./src/app/shared/*
folder location. Any sub folders, say services
andcomponents
, are covered in this single definition, and the imports would look like this:
import { SomeSharedComponent } from ‘@shared/components/some-shared-component.component’;
import { SomeSharedService } from '@shared/services/some-shared-service.service';
Conclusion
Importing via absolute paths makes your imports clean and more readable. I hope you found this article helpful for your Angular apps. Post your questions in the comments and I’ll get back to you! Thanks for reading!
You can find me on Twitter, GitHub, LinkedIn, and my website!