You have unlimited access as a PRO member
You are receiving a free preview of 3 lessons
Your free preview as expired - please upgrade to PRO
Recent Posts
- Object Oriented Programming With TypeScript
- Angular Elements Advanced Techniques
- TypeScript - the Basics
- The Real State of JavaScript 2018
- Cloud Scheduler for Firebase Functions
- Testing Firestore Security Rules With the Emulator
- How to Use Git and Github
- Infinite Virtual Scroll With the Angular CDK
- Build a Group Chat With Firestore
- Async Await Pro Tips
Shorten TypeScript Imports in an Angular Project
Episode 79 written by Jeff DelaneyIn 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
.
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 |
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 |
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'; |
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 |
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.