【问题标题】:Angular 2 can you import something from the project root instead of having to go back using ../Angular 2 你可以从项目根目录导入一些东西,而不必使用 ../
【发布时间】:2017-02-28 18:15:43
【问题描述】:

我发现我正在慢慢地挖自己的坟墓,因为我的文件夹结构越深,每次需要从根组件导入模块时,我必须越往后走:

import {ComponentsModule, SharedModule} from '../../../../../../shared';

由于该视图也有子视图,因此它会变得更长。

我查看了this question,这表明到目前为止,Angular 2 无法做到这一点。然而,这对我来说似乎很奇怪,以至于没有办法实现这样的目标:

import {ComponentsModule, SharedModule} from 'src/app/shared';

这是将来会出现的功能,还是已经可能以某种方式实现?

编辑:根据@Sasxa 的建议,我这样做了:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "*": [
        "*"
      ]
    },
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es6", "dom"],
    "mapRoot": "./",
    "module": "es6",
    "moduleResolution": "node",
    "outDir": "../dist/out-tsc",
    "sourceMap": true,
    "target": "es5",
    "typeRoots": [
      "../node_modules/@types"
    ]
  }
}

但是现在,当我尝试启动 Angular CLI 时,我得到了一大堆错误,主要是这些:ERROR in Entry module not found: Error: Recursion in resolvingERROR in multi main Module not found: Error: Recursion in resolving

有什么遗漏吗?

【问题讨论】:

  • 几个月前我一直在研究这个问题,可以通过制作导出东西的节点模块(有点像你从'@angular'导入)。我发现了这个:github.com/Microsoft/TypeScript/issues/5039,它接缝了一些选项已添加到tsconfig。我也得研究一下(;

标签: angular typescript import


【解决方案1】:

这似乎可以通过tsconfig.json 中的pathsbaseUrl 编译器选项来完成。 https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

这是来自文档的示例:

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "*": [
                    "*",
                    "generated/*"
                ]
            }
    }
}

这告诉编译器对于匹配模式“*”(即所有值)的任何模块导入,在两个位置查找:

  • “*”:表示同名不变,所以map => \
  • "generated*" 表示模块名称附加前缀“生成”,所以 map => \generated\

应该在 TypeScript 1.9+ 中可用


更新:

我刚刚尝试过:添加"baseUrl": "." 允许我在我的应用程序的任何位置添加import {...} from 'app/shared'(我的tsconfig.jsonsrc\ 文件夹中)。编译没有任何错误,并且可以使用 Angular CLI。

【讨论】:

  • 是的,我只是在一个文件里改了,其余的还是../../
  • 不带路径试试,我刚用baseUrl
  • 啊,生病的兄弟。这将帮助我很多!希望我能给你投票 x100 :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-10
  • 2017-11-14
  • 2014-09-11
  • 1970-01-01
  • 2017-07-28
  • 1970-01-01
相关资源
最近更新 更多