简体   繁体   English

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

[英]Cannot shorten import paths with tsconfig.json

The paths I defined in tsconfig.json do not work.我在 tsconfig.json 中定义的路径不起作用。

I started a project with Ionic 4 and wanted to avoid ugly paths in the imports.我用 Ionic 4 开始了一个项目,并希望避免导入中的丑陋路径。 I found information about modifying tsconfig.json, which I did.我找到了有关修改 tsconfig.json 的信息,我就是这样做的。 I already found these answers: How to use paths in tsconfig.json?我已经找到了这些答案: 如何在 tsconfig.json 中使用路径? and Cannot resolve tsconfig paths并且无法解析 tsconfig 路径

So my tsconfig.json looks like this:所以我的 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/*"]
    }
  }
}

And I access a class that specifies a user in my service:我访问了一个在我的服务中指定用户的类:

import { User } from '@data/User';

The User class looks like this: User 类如下所示:

export class User {
   ...
}

My project structure looks like this:我的项目结构如下所示:

在此处输入图片说明

I don't see any difference between my code and the different solutions I shared.我没有看到我的代码和我共享的不同解决方案之间有任何区别。 The error shown is:显示的错误是:

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

What am I doing wrong?我究竟做错了什么?

You should change your config like this你应该像这样改变你的配置

"paths": {
  "@services/*": ["src/app/services/*"],
  "@data/*": ["src/app/data/*"]
}

Because the path should be start from src folder因为路径应该从 src 文件夹开始

Then you can import like然后你可以像这样导入

import { User } from '@data/User';

Advices for Typescript paths(especially in Angular CLI context) Typescript 路径的建议(尤其是在 Angular CLI 上下文中)

  1. After setting Paths inside your tsconfig.json you should restart your server in order to make it works as expected.tsconfig.json设置Paths后,您应该重新启动服务器以使其按预期工作。

  2. Always make sure your path begin with the root folder in order to avoid possible errors eg using the src folder as root.始终确保您的路径以根文件夹开头,以避免可能的错误,例如使用src文件夹作为根文件夹。

I used the paths option several times and with varying results.我多次使用paths选项,结果各不相同。 Unfortunately, it never works as well as you would expect.不幸的是,它永远不会像您期望的那样工作。 The first thing you should try is to delete your dist and recompile your project from scratch and check that the transpiled javascript has indeed produced the right import paths (eg .js files have the complete paths in them).您应该尝试的第一件事是删除您的 dist 并从头开始重新编译您的项目,并检查转换后的 javascript 是否确实生成了正确的导入路径(例如 .js 文件中包含完整路径)。 Usually recompiling a few times works.通常重新编译几次即可。

Then I suggest to rely on your IDE to be sure that your paths are written correctly, for example, VSCode should able to resolve your imports and you should be able to navigate through cmd+click or ctrl+click on your imports.然后我建议依靠您的 IDE 来确保您的路径写入正确,例如,VSCode 应该能够解析您的导入,并且您应该能够通过 cmd+click 或 ctrl+click 导航您的导入。 If VSCode is not navigating your imports correctly, most probably you need to check your tsconfig again (even though it looks correct from your screenshot).如果 VSCode 没有正确导航您的导入,您很可能需要再次检查您的 tsconfig(即使它从您的屏幕截图中看起来是正确的)。

Also, an important note is that paths is ignored when performing tests with jest/ts-jest, if that is what your are trying to achieve then you need to map paths in your jest configuration as well using the modeuleNameMapper options like this:另外,一个重要的注意事项是在使用 jest/ts-jest 执行测试时忽略paths ,如果这是您想要实现的目标,那么您需要在 jest 配置中映射路径以及使用如下所示的modeuleNameMapper选项:


  moduleNameMapper: {
    '^@finder/(.*)$': '<rootDir>/files-manipulation/$1',
    '^@metadata/(.*)$': '<rootDir>/folder-metadata/$1',
    '^@logger/(.*)$': '<rootDir>/logging/$1',
  },

The following worked for me in 2021:以下内容在 2021 年对我有用:

a) Modify your tsconfig.json file to resemble the following: a) 将您的tsconfig.json文件修改为如下所示:

"compilerOptions": {
  "baseUrl": "./",
  "paths": {
    "@environment/*": ["./src/environments/*"],
    "@app/*": ["./src/app/*"],
    "@core/*": ["./src/app/_core/*"],
    "@shared/*": ["./src/app/_shared/*"]
  }

b) Restart your server. b) 重新启动您的服务器。

c) Use the paths mentioned in tsconfig.json file as shown in the example below: c) 使用tsconfig.json文件中提到的路径,如下例所示:

import { CategoriesService } from "@shared/services/categories/categories.service";

d) Ensure that you modify the above import to match your own directory structure. d) 确保您修改上述导入以匹配您自己的目录结构。 That's it!就是这样!

I didn't make such thing before but i think if you change this file you chould also change the app.modules.ts for service path.我以前没有做过这样的事情,但我认为如果你改变这个文件,你也应该改变服务路径的 app.modules.ts 。 And in app.routing.ts you should change the import path of the class to the new one since it starts with default ./ and you changed it.在 app.routing.ts 中,您应该将类​​的导入路径更改为新路径,因为它以默认 ./ 开头并且您更改了它。 And in user.module.ts i think you should also change.在 user.module.ts 我认为你也应该改变。 Thats not an answer but suggestion to see if thats the problem Regards.这不是答案,而是建议,看看这是否是问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM