Simpler Typescript paths with path aliases

Share on facebook
Share on google
Share on twitter
Share on linkedin

For a long time, I have felt the pain of maintaining relative paths in an application with typescript. You move something and you need to fix the path in 10+ files without easily being able to fix the paths. Also sometimes you see a long import path like “../../../../../../../../../app/config/config.ts“, ugly right? Fear not, typescript path alias has come to the rescue.

Typescript aliases allow you to specify a word/alias for an absolute path in the application from which you can resolve paths from absolutely. This means that you can have an alias called @app for the absolute path “src/app” and if you wanted to import a module from “src/app/config/config.ts” you would import it like “@app/config/config.ts” from everywhere in your application! Now every other file that imports config.ts will have the exact same path, so if you want to move config.ts at some point, you would be able to just do a find and replace for the path.

How to setup Typescript path alias

You set up a Typescript path alias in your tsconfig like this:

You set a baseUrl for resolving path with baseUrl. For an Angular CLI app I’m setting the baseUrl to “src”.
The paths are specified as an object with path alias keys and paths to resolve from, relative to the specified baseUrl.

And now you have a path alias called @app you can use like this:

Straight to the point, this is how you can save yourselves from maintaining relative paths in your application and instead have absolute typescript path which is easier to maintain.

This is implemented here:

Do you want to become an Angular architect? Check out Angular Architect Accelerator.

Related Posts and Comments


How To Become An In-Demand Angular Architect & Accelerate Your Career In 8 Weeks The Angular Architect Accelerator online program’s next cohort will soon be kicked off! Sign up now by email to learn more and secure a seat for the free warmup workshop. Enrollment is currently closed but the next cohort will start soon…  Sign up to get notified about the

Read More »

Walkthrough: Building An Angular App Using Tailwind CSS and Nx

In this video, we will cover a walk-through from scratch covering how to Build and Angular app using Tailwind CSS and Nx including Angular standalone components. 🖌 Tailwind CSS setup and usage⚙️ Nx monorepo configuration🧍‍♂️ Standalone components✅ Building a complete app in less than 2 hours with best practices ⏳ Timestamps:0:00 – Intro1:00 – Tailwind

Read More »