Reputation: 16726
I tried madge
on a TypeScript app that I'm working on:
npx madge --circular --extensions ts src/
And got a long dump of circular dependencies (61 of them actually). The thing is however that app compiles and works fine. How is this possible? Are there certain conditions when circular dependencies turn into the problem?
Upvotes: 1
Views: 1523
Reputation: 6561
Synchronous circular imports are fine, generally. Think of them as declarations, they don't actually perform anything. Just as long as you don't use the imports immediately, synchronously. For instance, this works:
A.js:
import B from 'B.js'
export function A() {
if (/* some condition that doesn't last forever */) return B()
else return 0 // of course, you don't want an infinite recursive loop either ;)
}
B.js:
import A from 'A.js'
export function B() {
if (/* some condition that doesn't last forever */) return A()
else return 0 // same thing
}
You can import A and B in another file, and call both of them there, it'll be fine. A and B refer to each other but they don't need to use each other until one of them is called.
But if you use one of the two exports synchronously while the other isn't exported yet, that will fail:
A.js:
import B from 'B.js'
export const A = B(something)
B.js:
import A from 'A.js'
export function B() {
return A
}
Now what happens here is that the evaluation of A (which must be performed before exporting it) requires calling B, and running B requires that A is already defined.
Upvotes: 2