【问题标题】:using path on tsconfig.json doesn't resolve using angular在 tsconfig.json 上使用路径不能使用 angular 解决
【发布时间】:2017-12-09 09:01:30
【问题描述】:

为了避免导入文件时的相对路径,我尝试配置角度来理解路径。

到目前为止,它根本不起作用,我的代码:

//tsconfig.app.json
"compilerOptions":{
    //lot of things . If it matter moduleResultion is set to node
    "baseUrl": ".",
    "paths": {
        "@modules": ["app/modules/"]
        ...
    },
}



//in a component: 
import { X } from '@modules/Y/component/index'

运行 ng serve 时,控制台输出错误:: Cannot find module '@modules/Y/component/index'.

这绝对适用于像import { X } from ../../../modules/Y/component/index这样的相对路径

所以,我希望我的 tsconfig.app.json 或 tsconfig.json(或两者都有)是错误的,但是,我找不到任何关于如何为 Angular 应用程序正确执行此操作的好的教程。

目前使用 angular 4 和基本的关联工具(typescript 2.3.3、angular-cli 1.0.6 并提供 webpack)

你能向我指出这个问题,或者给我一个很好的文档/教程,用角度解决这个问题吗?到目前为止,我在 SO 或 github 问题上看到的所有答案都没有奏效。

注意:架构看起来像这样

project
   |
   -tsconfig.json //had try things on this one too but does nothing.
   -src/
     |
     -tsconfig.app.json
     -app/
       |
       -modules
       -othersFolder

【问题讨论】:

  • 您是如何设置项目的? ng new 通常设置好,你很高兴....
  • 我确实在 Angular 还在 RC2 上时使用 ng-cli 进行了设置。
  • 如果您使用的是 VSCode 之类的东西,如果您右键单击导入语句中的类,您可以使用 Goto Definition 导航到源代码。如果您的相对路径不正确,编辑人员通常会做一些事情,例如在路径下放置波浪线。那我会检查的。
  • 我还会检查您是否正确设置了 app-modules.ts。 angular.io/guide/ngmodule
  • 我在 ST。 goto 工作正常,但在控制台中仍然无法正常工作,所以必须是别的东西。

标签: angular typescript webpack angular-cli


【解决方案1】:

您的代码应该可以使用

"paths": {
  "@modules/*": ["app/modules/*"]
  ...
}

在此处阅读有关 typescript 中模块解析的更多信息

https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

【讨论】:

  • 直到 19 点才能提供赏金。
  • 区别(与问题中的第一个代码示例)是在模块名称后使用/*? (“路径”仍然是编译器选项的子项?)
猜你喜欢
  • 2017-09-03
  • 2021-02-20
  • 2019-12-03
  • 2019-02-09
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
相关资源
最近更新 更多