无法使用 tsconfig.json 缩短导入路径

Axl*_*996 5 single-page-application typescript ecmascript-6 ionic-framework angular

我在 tsconfig.json 中定义的路径不起作用。

我使用 Ionic 4 启动了一个项目,希望避免导入中出现丑陋的路径。我找到了有关修改 tsconfig.json 的信息,我就这么做了。我已经找到了这些答案: How to use paths in tsconfig.json? 并且 无法解析 tsconfig 路径

所以我的 tsconfig.json 看起来像这样:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./src",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "@services/*": ["app/services/*"],
      "@data/*": ["app/data/*"]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我访问一个在我的服务中指定用户的类:

import { User } from '@data/User';
Run Code Online (Sandbox Code Playgroud)

User 类如下所示:

export class User {
   ...
}
Run Code Online (Sandbox Code Playgroud)

我的项目结构如下所示:

在此输入图像描述

我没有看到我的代码和我共享的不同解决方案之间有任何区别。显示的错误是:

[ng] src/app/services/profile.service.ts(3,22) 中的错误:错误 TS2307:找不到模块“@data/User”。[ng]

我究竟做错了什么?

bil*_*jov 1

关于 Typescript 路径的建议(特别是在 Angular CLI 上下文中)

  1. 在内部设置路径tsconfig.json后,您应该重新启动服务器以使其按预期工作。

  2. 始终确保您的路径以根文件夹开头,以避免可能的错误,例如使用该src文件夹作为根文件夹。