Cleanup relative paths in Angular/Typescript

By: Chris Dunn

Angular projects usually start out pretty simple with a similarly simple folder structure.   Most likely in the beginning you simple drop all components, directives and services in the /app folder just to get things working.  As your program grows, you realize (hopefully) that if you're going to survive you will need to apply some sort of structure moving forward.

This can cause it's own problems by turning our nice, short import statements from this:

Import { MyComponent } from './mycomponent.component';

Into something like this:

Import {MyComponent} from '../../../../app/components/mycomponent/mycomponent.component';

The good news is that typescript has you covered with a simple solution that will leave you with clean, readable code.  The solution is to create aliases for common paths, and use those in place of the inline relative paths.

Import {MyComponent} from '@components/mycomponent.component';

To do this, open up the tsconfig.json file in your application root folder.  Within the compiler options, you will need to add the baseUrl value of "src" or wherever your starting path for you aliases will be.  Next add the "paths" values.  The @ symbol is not necessary and only a personal preference.  The value is an array of paths which is why it's enclosed in brackets. Within paths, you can define commonly used file paths to make your code cleaner and more readable.

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@services/*": [ "app/services/*" ],
      "@components/*": [ "app/components/*" ]
    },
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}
Tags: angular typescript

Copyright 2023 Cidean, LLC. All rights reserved.

Proudly running Umbraco 7. This site is responsive with the help of Foundation 5.