I have a theory about what is happening, though I haven't tried running the code in a debugger to make sure:
- a.js runs and imports c.js
- c.js runs and imports b.js (before
c
is defined!) - b.js runs and imports c.js. But c.js does not run again, because it has already been imported once before.
- Since
c
is still undefined in the c.js scope (becausec.js
has not continued running yet; it is still waiting for theimport
call on line 2 to return),c = undefined
is injected into the b.js scope. - b.js finishes executing.
- c.js finishes executing.
- a.js finishes executing.
So b.js never receives a valid binding for c
, and b.init()
throws an exception when it tries to access c.foo
.
If this theory is correct, I think you could fix the error by moving the import calls in b.js and c.js to the bottoms of those files.