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

product page

It’s time to become a highly paid Angular developer

Proven Process​ Become an Angular architect by following practical step-by-step instructions that are proven to

Read More »