Search Lessons, Code Snippets, and Videos
search by algolia
X
#native_cta# #native_desc# Sponsored by #native_company#

Shorten TypeScript Imports in an Angular Project

Episode 79 written by Jeff Delaney
full courses and content on fireship.io


In this lesson, I will show you how to use TypeScript path mapping to make import statements in your Angular app shorter and much more developer-friendly. As you know, an Angular app’s file structure can be relatively deep, making it difficult to figure out where a module lives when importing it. The idea is to make your import paths go from ../../../../ to @namespace.

shorter relative import paths in Angular

The Problem - Super Long Import Statements

Let’s arbitrarily create a deeply nested component in Angular and a service to go along with it.

ng g component shared/deeply/nested/hello-world
ng g service core/my

When you have a large Angular project with deeply nested files and folders it leads to import statements that look like this…

// import from component.ts
import { MyService } from '../../../../my.service';

// import from service.ts
import { HelloWorldComponent } from '../shared/deeply/nested/hello-world/hello-world.component';

That’s might be fine occasionally, but it becomes very annoying and difficult to maintain for each new component you build. Furthermore, moving a file will require you to rewrite every path to the new location.

The Solution - TypeScript Config

Fortunately, we can configure TypeScript to make our files behave more like a monorepo by namespacing commonly used paths. All paths will be resolved relative to the baseUrl, which should be the src directory in an Angular CLI project.

You can then point to any directory in your project and give it a custom namespace. Any name will work, but watch out for name collisions with existing node packages, i.e. @angular, @ngrx, etc. The end result looks like…

import { MyService } from '@services/my.service';

import { HelloWorldComponent } from '@components/hello-world.component';

Much nicer! And we never need to think about the relative file location of an import - a simple, yet powerful productivity booster.

We can make this possible by configuring TypeScript to use custom namespaces to point to specific paths.

// tsconfig.json in the root dir

{
"compileOnSave": false,
"compilerOptions": {

// omitted...

"baseUrl": "src",
"paths": {
"@services/*": ["app/path/to/services/*"],
"@components/*": ["app/somewhere/deeply/nested/*"],
"@environments/*": ["environments/*"]
}
}
}

The End

Not much to it, but that’s one of my favorite productivity boosters in Angular. Let me know what you think in the comments or via Slack.