Absolute path in Angular cli project

[亡魂溺海] 提交于 2020-01-24 10:28:22

问题


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'


回答1:


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.




回答2:


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";


来源:https://stackoverflow.com/questions/41307024/absolute-path-in-angular-cli-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!