6

How can I use absolute path in an angular cli generated project?

So I have this path : src -> app -> shared and I would like to write import {} from 'shared/ffdsdf/my.module.ts' instead of '../shared/ffdsdf/my.module.ts'

Alessio
  • 3,134
  • 19
  • 36
  • 46
user3409988
  • 315
  • 2
  • 5
  • 16

3 Answers3

17

better sample:

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@app/*": [
        "app/*"
      ],
      "@app/core/*": [
        "app/core/*"
      ],
      "@app/shared/*": [
        "app/shared/*"
      ],
      "@env/*": [
        "environments/*"
      ]
    }
  }
}

use:

import { someService } from "@app/core/some.service";

instead of:

import { someService } from "./../../core/some.service";
Mironline
  • 2,654
  • 7
  • 33
  • 58
Masoud Bimmar
  • 8,635
  • 4
  • 26
  • 32
11

There is a TypeScript feature that allows this.

You can modify your src/tsconfig.json file to enable this, under compilerOptions, add the following:

{
  "compilerOptions": {
    // ...
    "paths": {
      "*": [
        "./*",
        "app/*",
        "../node_modules/*"
      ]
    }
}

You can obviously change the pattern key and values as needed. You add or remove folders, you can change the order, etc.

You can also choose a prefix instead of just * (especially if it cases problems), you can use something like ~/*, and your imports will then be all from '~/shared/sample' etc.

Meligy
  • 34,211
  • 11
  • 83
  • 106
  • i have paths like below, can you help me with proper structure that i have to use "paths": { "~appCore/*": [ "app/core/*" ], "~appCommon/*": [ "app/common/*" ] }, – Charan Giri Aug 23 '18 at 18:51
  • 1
    What happens with these paths mappings if the project defining them is a library ? How will the client application not break when hitting these unknown paths in the installed library ? – Stephane Jul 15 '19 at 12:54
0

In Angular9, it's important to follow the following steps.

  1. Create baseUrl and path in tsconfig.json

    {
 "baseUrl": "./src",
    "paths": {
      "@angular/*": [
        "../node_modules/@angular/*"
      ],
      "@app/*": ["app/*"],
      "@views/*": ["app/views/*"],
      "@containers/*": ["app/containers/*"]
    }
}

Note: Here you can see that I have also added @angular path resolution to tsconfig.json. This step will ensure VSCode to show the correct syntax highlighting.

  1. Remove baseUrl and path from tsconfig.app.json

Note: Without doing this step, you will get the module not found error when compiling the angular project. (Syntax highlighting was fine even without this).

Ashan
  • 17,521
  • 3
  • 39
  • 62