【问题标题】:How to convert relative import to absolute in angular 6?如何在角度 6 中将相对导入转换为绝对导入?
【发布时间】:2018-09-22 21:34:33
【问题描述】:

如何在 Angular 6 中将相对导入转换为绝对导入?

例如

environments/environment 代替

 ../../../../environments/environment

【问题讨论】:

  • 在 typescript/javascript 领域,“绝对”名称实际上意味着“以该名称在 npm 上发布”。试图规避这一点是不值得的。
  • 我的解决方案对您有用吗?

标签: angular typescript import


【解决方案1】:

这实际上是针对 TypeScript,不一定是 Angular。以下是您需要添加到项目根目录中的 tsconfig.json 文件的示例:

{
  // Other TS options here
  "compilerOptions": {
    // more stuff is usually here
    "paths": {
      "@constants/*": ["./app/constants/*"],
      "@components/*": ["./app/components/*"],
      "@directives/*": ["./app/directives/*"],
      "@env/*": ["./environments/*"],
      "@models/*": ["./app/models/*"],
      "@services/*": ["./app/services/*"],
      "@states/*": ["./app/state-management/*"]
    }
  },
  // ...other stuff can be here too
}

然后,您将能够在您的特定文件/组件中执行此操作:

import { LoggerService } from '@services/logger/logger.service';

【讨论】:

  • 另外,你应该添加 ""baseUrl": "src","
  • @MaxKarpovets => 这就是为什么我在它周围做 cmets 让 OP 选择其他需要在那里的部分原因。
  • 可以使用绝对路径吗?例如 "C:/aaaa/app/constants/*" 而不是 "./app/constants/*"
  • @ps0604 => 我不确定。我所做的一切都是相对进口的,所以你必须测试它。抱歉,我不能提供更多帮助。
  • @th3n3wguy 我尝试了一个绝对路径,它成功了。这样我就可以与两个项目共享一个目录。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多