【问题标题】:Angular2 import absolute path or custom path (typescript 2)Angular2导入绝对路径或自定义路径(打字稿2)
【发布时间】:2017-03-13 17:07:01
【问题描述】:

在我们的 angular2 项目中,我们将所有模型 ts 文件放在一个特定文件夹中:/app/common/model/*. 我可以用亲戚路径在我的组件中调用它们,但这非常费力。 所以 2 个解决方案,最好是自定义路径:StackOverflow: Relative Paths for SystemJS & ES module imports。 但是我的 IDE 找不到路径。这是我的 tsconfig :

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "built",
    "baseUrl": ".",
    "paths": {
      "mymodel/*": [
        "app/common/model/*"
      ]
    }
  }
}

在我的组件中: import { Address } from 'mymodel/address.model';

IDE:[ts] 找不到模块.... 我尝试在路径中使用或不使用 *

第二个解决方案:Stackoverflow: Angular 2, imports between different folders

IDE 和编译都可以,组件中有完整路径: import { Address } from 'common/model/address.model';

还有 tsconfig:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "built",
    "baseUrl": ".",
    "paths": {
      "*": [
        "app/*",
        "node_modules/*"
      ]
    }
  }
}

但我们对所有模型的页面加载都为 404。 也许是 systemjs 文件中的配置?

在这两种情况下,我认为“outdir”参数是问题所在,我们缺少一些东西。

非常感谢您的帮助!

问候,

打字稿:2.0.6 角度:2.0.0

【问题讨论】:

  • 您使用的是哪个 IDE?在我的(IntelliJ/Webstorm)中,我几乎从不输入导入:IDE 为我添加了它。
  • Visual Studio 代码。在你那里是绝对路径吗?
  • 第一个解决方案与其他 IDE 配合得很好......对不起,这是一个虚假的问题

标签: angular typescript path tsconfig


【解决方案1】:

在通过互联网搜索尝试了解究竟是什么问题并尝试不同的故障排除选项后,我开始了解 baseUrl 和 Path 如何协同工作

注意:此解决方案适用于 Angular Cli 1.x。不确定其他工具,

如果你像下面这样使用 baseUrl:"." 它可以在 VScode 中工作,但不能在编译时

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": ".",
    "paths": {
      "@myproject/*": ["src/app/*"]
    }    
}

据我的理解和我的工作应用程序并签入 angular aio 代码,我建议使用 baseUrl:""src 如下所示

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "paths": {
      "@myproject/*": ["app/*"],
      "testing/*": ["testing/*"]
    }    
}

通过将基本 URL 作为源(src 目录),编译器可以正确解析模块。

我希望这有助于人们解决此类问题。

【讨论】:

  • "如果你使用 baseUrl:"." 如下所示,它在 VScode 中有效,但在编译时无效" - 这非常重要。谢谢
  • 这是否适用于较新的版本,因为我已经尝试了所有方式,但无法参考上述路径。
猜你喜欢
  • 1970-01-01
  • 2022-11-05
  • 2013-04-17
  • 2016-06-06
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
相关资源
最近更新 更多