Simplifying Typescript import paths in Angular

Photo by Vidar Nordli-Mathisen on Unsplash

Before we begin…we need to answer 2 questions

  1. Can this be applied to any other typescript project as well?

Yes, the methodology discussed in this article isn’t limited to Angular only and with very few modifications can be used with other typescript projects as well, but for the sake of simplicity I am going to keep demonstrate it using Angular.

2. Is it worth doing?

YES & NO, if you are working on a small scale project then it’s trivial to use but imagine having 4 to 5 levels of nested directories where the import path starts with something like “../../../../../../”, CRAZY right!

import { RadioButton } from '../../../../../../shared/components/forms/radio-button/radio-button.component';

Imagine this being used in more than 10 components and now you have to move it into the controls directory (refactoring), well you’ll have to update paths in at least 10 files, maybe more.

But if you love those commits where GitHub shows 10 files changed just because you moved a single file, nobody is going to judge you, it’s more sort of a personal preference. 🤓

Without further ado let’s see how to shorten import path using Typescript tsconfig.json file.

You only need to update your tsconfig.json

You can update tsconfig.json but if you are using Angular 6+ you can add this configuration in tsconfig.app.json so that you can specify different paths based on the project or library you are working on a CLI Project

And instead of importing your files like this:

import { RadioButton } from '../../../../../../shared/components/forms/radio-button/radio-button.component';

You can import it like this:

import { RadioControl } from "@controls/radio";
import { environment } from "@environment/environment"

Much better, Right! 😎

NOTE: @ in the start of path isn’t mandatory, you can use short paths without it.

PROS

  • Short import statements
  • Single line change when file is moved to different directory, unless short path points to directory rather than a file

CONS

  • No intellisense for paths (Webstorm supports upto some extend)

Thanks for reading, if you have suggestions or comments, let us know 😇