【问题标题】:Nest dependency resolution issue with tsconfig paths and barrel files/same directory importstsconfig 路径和桶文件/相同目录导入的嵌套依赖项解析问题
【发布时间】:2019-09-07 04:53:07
【问题描述】:

我在 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';

【问题讨论】:

  • 你能在src/services中显示你的index.ts吗?
  • @ford04 我已经用src/services 中的index.ts 文件更新了我的问题。

标签: typescript nestjs tsc


【解决方案1】:

出口订单事宜

在我的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 中的问题。

【讨论】:

    猜你喜欢
    • 2017-02-22
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多