Menu

Reference Angular Imports Absolutely for Easier Development ― Scotch

November 4th, 2017

  • Our goal for this will be to reference things like so: – import { HeaderComponent } from { FooterComponent } from { GifService } from is similar to how Angular imports are referenced using @angular like @angular/core or @angular/router.
  • Setting Up Absolute Paths – Since TypeScript is what is in charge of transpiling our Angular apps, we’ll make sure to configure our paths in tsconfig.json.
  • In the tsconfig.json, we’ll do two things by using two of the compiler options: – baseUrl: Set the base folder as /src – paths: Tell TypeScript to look for @app in the /src/app folder – baseUrl will be the base directory that is used to resolve non-relative module names.
  • { – “compileOnSave”: false, – “compilerOptions”: { – … – – “baseUrl”: “src”, – “paths”: { – “@app/*”: [“app/*”] – } – } – } – With that in our tsconfig.json, we can now reference items absolutely!
  • import { HeaderComponent } from { FooterComponent } from { GifService } from is great because we can now move our files around and not have to worry about updating paths everywhere.

Working with Angular has been a delight. Working with TypeScript, Observables, and the CLI have been great tools for development.

Working with Angular has been a delight. Working with TypeScript, Observables, and the CLI have been great tools for development.

Referencing Imports Relatively

One piece of feedback I’ve noticed when working with Angular is when importing components and classes around your application.

Take the following for example:

import { HeaderComponent } from { FooterComponent } from { GifService } from the imports here are referenced relatively. It can be a hassle to remember how many folders to jump into and out of.

If you move your files around, you’ll have to update all your import paths.

Let’s look at how we can reference imports absolutely so that TypeScript always looks at the root /src folder when finding items.

Our goal for this will be to reference things like so:

import { HeaderComponent } from { FooterComponent } from { GifService } from is similar to how Angular imports are referenced using @angular like @angular/core or @angular/router.

Setting Up Absolute Paths

Since TypeScript is what is in charge of transpiling our Angular apps, we’ll make sure to configure our paths in tsconfig.json.

In the tsconfig.json, we’ll do two things by using two of the compiler options:

baseUrl: Set the base folder as /src

paths: Tell TypeScript to look for @app in the /src/app folder

baseUrl will…

Reference Angular Imports Absolutely for Easier Development ― Scotch