Why does require() return "an unfinished copy" of a module exports instead of a reference to it (circular dependency)?

Viewed 44

The usual behaviour of the require() function is to use caching. So if several modules request another one, all of them get references to the very same object represents exports of the required. However, according to the docs there is an exception:

When main.js loads a.js, then a.js in turn loads b.js. At that point, b.js tries to load a.js. In order to prevent an infinite loop, an unfinished copy of the a.js exports object is returned to the b.js module. b.js then finishes loading, and its exports object is provided to the a.js module.

Such behaviour tends to facilitate inconsistency due to what a module receives from require() depends on the precedence this module was given itself (b.js was required after a.js, so the former gets an unfinished copy of a.js export, whereas the latter has a direct reference to b.js export).

What's the rationale for this approach? Why is it impossible to return a cached version of a.js export to b.js (which was created when main.js requested a.js)?

0 Answers
Related