【发布时间】: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