首页 > 解决方案 > 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';

标签: typescriptnestjstsc

解决方案


出口订单事宜

在我的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.


推荐阅读