Short Typescript Import Paths in Angular 7

This is an update for Angular 6/7 to the method described here for shortening typescript imports in deeply nested files from something like this:

import { DeepSharedComponent } from ../../../../shared/components/deep-shard-component;

to something like this:

import { DeepSharedComponent } from @shared/components/deep-shared-component;

Basically, we use the same method outlined above, but move the paths entry from tsconfig.json to tsconfig.app.json, and ensure that the baseUrl entries in tsconfig.json and tsconfig.app.json point to the same directory, keeping in mind that tsconfig.app.json is located one directory below tsconfig.json.

Example:

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": [],
    "baseUrl": "../",
    "paths": {
      "@app/*": ["./src/app/*"],
      "@assets/*": ["./src/assets/*"],
      "@core/*": ["./src/app/core/*"],
      "@environments/*": ["./src/environments/*"],
      "@features/*": ["./src/app/features/*"],
      "@shared/*": ["./src/app/shared/*"]
    }
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

Notice that baseUrl in the tsconfig.app.json file is set to "../" while baseUrl in the tsconfig.json file is set to "./". This is because the CLI file structure for the current version of Angular (7.2.9 as of the date of this article) looks like this:

project
    |--e2e
    |--mocks
    |--node_modules
    |--src
        |--app
        |  ...
        |--tsconfig.app.json
    |--tsconfig.json

The CLI automatically sets baseUrl in tsconfig.json to "./" so that it points to the project directory. We need to make sure that the baseUrl in tsconfig.app.json file also points to the project directory. In order to do that, we need to set baseUrl to "../" (one level up from the directory in which the tsconfig.app.json file sits).

One this is done, Angular should be able to properly resolve paths that are dependent on tsconfig.json--such as URLs in your CSS code--as well as resolve typescript import path maps placed in the tsconfig.app.json file.

Short Typescript Import Paths in Angular 7

This is an update for Angular 6/7 to the method described here for shortening typescript imports in deeply nested files from something like...