When an Angular application contains several modules or sub-folders, it can become challenging to maintain the readability of your Typescript imports. For instance:
import {something} from '../../../../../shared/shared.service'
It’s always better to rely on your IDE to write those paths for you using autocompletion (usually ctrl + space). Still, imports don’t have to be that long. Typescript has a solution for that called path mapping.
The idea is to define common paths in the tsconfig.json file of your projects. Then, in the compilerOptions
property, add or edit the paths config to provide some aliases for all of your long paths:
"paths": {
"stubs/*": [
"./src/app/stubs/*"
],
"state/*": [
"./src/app/state/*"
],
"shared/*": [
"./src/app/shared/*"
]
}
The above results in a shorter import syntax everywhere in your code:
import {something} from 'shared/shared.service'
Of course, you can define as many path mappings as you need. Read that post for more of my favorite Typescript tips: 5 Typescript tricks for Angular. Some have already been covered in this newsletter, but all need reminders occasionally.