【问题标题】:Angular 10 - baseUrl and paths aren't workingAngular 10 - baseUrl 和路径不起作用
【发布时间】:2021-01-15 07:16:53
【问题描述】:

我正在尝试使相对 import 路由与 src/app/ 文件夹中的相对路径类似:

+ node_modules
+ src
| + app
| |  + services (just an example)
| |  |  -service.ts
| |  -app.module.ts (etc.)
| - tsconfig.app.json
- tsconfig.json
- package.json

基本上,我希望能够做到import { SomeService } from 'services/some.service'。但是,无论我在tsconfig.json(或tsconfig.app.json)中指定什么,一旦我执行ng serve,我都会收到一个错误,声称它不知道如何导入服务。

tsconfig.json:

{
  ...
}

src/tsconfig.app.json:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "paths": {
      "@angular/*": ["../node_modules/@angular/*"],
      "@services/*": [ "app/services/*" ],
      "@interfaces/*": ["app/interfaces/*"]
    },
    "baseUrl": "./",
    ...
  },
  ...
}

我的 Angular 和 Typescript 版本:

"@angular/core": "^10.2.3",
"typescript": "^3.9.7"

我错过了什么吗?

【问题讨论】:

    标签: angular tsconfig angular10


    【解决方案1】:

    我认为 baseUrl 应该是这样的:baseUrl: "./"。或者尝试将 baseUrl 设置为 src。这是我项目中的配置:

    "compilerOptions": {
      "baseUrl": "src",
      ...
      "paths": {
        "@core/*": ["app/core/*"],
        "@core/services": ["app/core/index.ts"],
        "@shared/*": ["app/shared/*"],
        "@state/*": ["app/state/*"]
      }
    },
    

    我正在使用 index.ts 文件重新导出所有服务,以便在导入时可以通过 @core/services 路径访问它们。

    我处理过类似的问题,也许你能找到一些灵感here

    【讨论】:

    • 不幸的是,效果并不好。我还尝试将所有内容放在扩展tsconfig.jsontsconfig.app.json 中。不幸的是,这(更新了上面的代码)也不起作用。
    • 嗯,这很奇怪。只是出于好奇,您是否尝试过删除/还原 tsconfig.app.json 中的更改?我已经看到多条说明如何设置路径别名,但我从未看到该文件中的更改。
    • 我已经做了一些 ahem “研究”,结果证明来自 tsconfig paths and module resolution errors in VS Code (GitHub) 的 Sandangel 的评论似乎有所帮助。
    【解决方案2】:

    tsconfig paths and module resolution errors in VS Code (GitHub)@sandangel 的评论中复制的解决方案似乎有所帮助:

    vscode 似乎只查看最近的 tsconfig.json 文件,而 角度读取您的 tsconfig.app.json 您应该添加相对路径 配置到 tsconfig.json 和 tsconfig.app.json。

    【讨论】:

      猜你喜欢
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 2023-03-03
      • 1970-01-01
      • 2013-07-06
      • 1970-01-01
      • 2018-03-23
      相关资源
      最近更新 更多