Typescript import 引用中的一个小坑
之前有一个奋斗了 N 小时才搞定的问题,在 Nestjs 的单元测试中反复测试会报类似于:
Starting Nest throws following error: Nest can't resolve dependencies of the EventResolver (EventService, ?). Please make sure that the argument at index [1] is available in the EventModule context.
Nest throws an error about a circular dependency that doesn't exist. Here is the error thrown:
Nest cannot create the module instance. Often, this is because of a circular dependency between modules. Use forwardRef() to avoid it. (Read more https://docs.nestjs.com/fundamentals/circular-dependency.) Scope [RootModule -> XXXModule]
两个问题,但是实际上,我们已经加上了 forwardRef,在开发时也没有遇到任何问题,只有当测试的时候遇到了问题,当时就非常困惑,在 debug 了半天之后发现是由于内部引用出现的问题,我们看下面这个 demo:
https://repl.it/@zefytt/Import-circulation-Demo
我们在调用 A 的时候,我们发现 console.log(B)
是 undefined,这是因为我们统一的在 index.ts
中暴露了:
export * from './a'
export * from './b'
而在 A 的依赖引入时 B 还没被初始化(可以看做一种深度优先遍历),导致引入的时候还是 undefined,所以在内部使用时会变成 undefined,如果我们使用浏览器进行 import,报错就相对友好,这一点可以交由同学们自己去实现。
在这个问题之后,我就把项目中所有希望引用路径尽可能短的 export *
index 文件都删掉了,这样才是降低心智负担最好的方式(尽管引用路径可能会更丑)。
评论 (1)
淦!遇到了同样的问题