DEV Community

Cover image for I take my morning coffee with a hint of Angular: Quick Tip #1 - Shortened import paths in TSConfig
Thomas Coucke
Thomas Coucke

Posted on

I take my morning coffee with a hint of Angular: Quick Tip #1 - Shortened import paths in TSConfig

In Angular development, long import paths can slow down large projects in the long run. TypeScript allows you to configure shortened import paths through the compilerOptions in your tsconfig.json file. It not only makes your code cleaner but also easier to maintain. When starting a project this is something you want to implement from the start. Projects get too big too fast with little time to refactor. This will save some time further on... .

Open your tsconfig.json file

The tsconfig.json file is usually located at the root of your Angular project. This is where you'll add the path mappings. If you have multiple apps, you can use the project-specific tsconfig-file like tsconfig.app.json

Add path mappings

Inside the compilerOptions section, add a paths property. This property is an object where the keys are the alias you want to use, and the values are arrays containing the actual paths.

{
   "compilerOptions":{
      "baseUrl":"./",
      "paths":{
         "@vinyl/*":["src/app/modules/music/collection/records/vinyl/*"]
      }
   }
}
Enter fullscreen mode Exit fullscreen mode

In this example, @vinyl/* will now refer to any file under the src/app/modules/music/collection/records/vinyl directory.

Using the aliases

With the aliases configured, you can now use them in your import statements. For instance, instead of using:

import { VinylRecordBuilder } from '../../../app/modules/music/collection/records/vinyl/vinyl-record.builder';
Enter fullscreen mode Exit fullscreen mode

you can use

import { VinylRecordBuilder } from '@vinyl/vinyl-record.builder';
Enter fullscreen mode Exit fullscreen mode
✅ Pros ⛔ Cons
Cleaner Code: Import statements are shorter and more readable.
Maintainability: Easier to refactor paths if your project structure changes.
Consistency: Enforces a standardized way of importing modules across your project.
No intellisense support

Top comments (1)

Collapse
 
jg-mike profile image
Michael Gichuhi

thank you so much it works