typescriptangular-cli

Absolute path in Angular cli project


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'


Solution

  • 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.