Simplifying RelativeImport Path Nightmare

Nested Paths In Large Application: Commonly, we have many feature components, Services, and other files in Large Applications. Sometimes these may be located in a multi-level folder structure like below. At first glance, we can

Nested Paths In Large Application:

Commonly, we have many feature components, Services, and other files in Large Applications. Sometimes these may be located in a multi-level folder structure like below.

import { ReadService } from '../../../../core/ImportReader.service.ts';
import { ImportService } from '../../../services/Imports.service.ts';

At first glance, we can say that its really hand to understand and error-prone for writing them. Plus if we end up changing the file location we would end up modifying all the files in which the file is imported.

Solution:

Typescript provides a great way to solve this kind of problem allowing us to customize a single global namespace for our Feature Modules. To eliminate long relative paths let’s add some options to our tsconfig.json located on the root of our Angular app:

  • baseUrl – Setting baseUrl informs the compiler where to find modules.
  • Add path settings inside CompilerOptions – It will be an object which keys are path aliases that you will be able to use in your code, and the values are arrays of paths the alias will be resolved to.
"CompilerOptions": {
        "baseUrl": "src",
        "paths": {
            "@Models/*": ["app/Models/*"],
            "@Enums/*":["app/Enums/*"]
        }
    }

Now we can use the below paths:

 
import { ReadService } from '@core/ImportReader.service.ts';
import { ImportService } from '@services/Imports.service.ts';
 

6 thoughts on “Simplifying RelativeImport Path Nightmare

Leave a Reply

Your email address will not be published. Required fields are marked *