typescript - tsconfig 路径和桶文件/相同目录导入的嵌套依赖项解析问题
问题描述
我在 tsconfig.json 中设置了一些不同的路径,以使控制器、实体、服务等的导入更容易处理。tsconfig.json 的相关部分:
...
"baseUrl": "./src",
"paths": {
"@hello/controllers": [
"./controllers"
],
"@hello/entities": [
"./entity"
],
"@hello/services": [
"./services"
]
},
...
我还在 src/controllers/、src/entity/ 和 src/services/ 目录中创建了桶文件 (index.ts),这些文件从这些目录中重新导出了我需要的所有类。
从我的控制器目录中的文件导入服务时,一切都按预期工作。例子:
// src/controllers/comment.controller.ts
// This works
import { CommentService } from '@hello/services';
@Controller()
export class CommentController {...}
从同一目录中的另一个服务文件导入服务时,事情不起作用。例子
// src/services/comment.service.ts
// This does NOT work
import { StoryService, UserService } from '@hello/services';
// StoryService, UserService, and CommentService are in the src/services directory
@Injectable()
export class CommentService {...}
执行上述操作时出现的错误是:
Error: Nest can't resolve dependencies of the CommentService (?, +). Please make sure that the argument at index [0] is available in the AppModule context.
预期的行为 我希望依赖项使用 tsconfig.json 中定义的路径来解决,即使它们是从同一目录中导入的。
可能的解决方案 我目前的解决方法是使用相对路径导入文件:
// src/services/comment.service.ts
// This does work
import { StoryService } from './story.service';
import { UserService } from './user.service';
// I'd prefer to do this:
// import { StoryService, UserService } from '@hello/services';
@Injectable()
export class CommentService {...}
环境 @nestjs/common@5.7.4 @nestjs/core@5.7.4 typescript@3.6.2
更新 我在 src/services 中的 index.ts 桶文件如下所示:
// src/services/index.ts
export * from './comment.service';
export * from './story.service';
export * from './user.service';
解决方案
出口订单事宜
在我的index.ts
桶文件中,我在用户和故事服务之前导出评论服务。但是,comment.service.ts 类会导入 story.service.ts 和 user.service.ts。必须在评论之前导出故事和用户。
前:
// src/services/index.ts
// This does NOT work
// and throws the "Nest can't resolve dependencies of the CommentService..." error
export * from './comment.service';
export * from './story.service';
export * from './user.service';
正确订购后:
// src/services/index.ts
// This works!
export * from './story.service';
export * from './user.service';
export * from './comment.service';
现在我可以在评论服务中使用我的 tsconfig.json 中的导入路径:
import { StoryService, UserService } from '@hello/services';
@Injectable()
export class CommentService {...}
感谢 @ford04 提示问题在index.ts
.
推荐阅读
- android - Google Play 控制台上的 Android 崩溃问题
- c++ - 如何在 C++ 中使用 cout 逐页打印?
- python - request.scope 中的 FastAPI 路由器不正确
- next.js - 请求后,数据未定义
- pivot - 使用数据透视表从日期范围按月显示职业百分比。谷歌表
- algorithm - 在 n 个值的数组中查找并排序 log2(n) 个最小值和 log2(n) 个最大值
- python - 是否可以在 Django 中添加用户过滤按钮
- ios - IOS 构建失败,在 GoogleService-Info.plist 中出现错误无效的 GOOGLE_APP_ID
- javascript - 如何解决未捕获的 TypeError:尝试使用 JS 和 html 显示当前时间时,无法在 printTime 设置 null 的属性(设置“innerHTML”)
- angular - TypeError:您在预期流的位置提供了“未定义”。您可以提供 Observable、Promise、Array 或 Iterable