You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Node.js 中的模块循环依赖
modules_cycles
当有循环的require调用时,模块返回时可能尚未完成它的执行
result:
翻译:当 main.js 加载 a.js 时, a.js 又加载 b.js。 此时, b.js 会尝试去加载 a.js。 为了防止无限的循环,会返回一个 a.js 的 exports 对象的 未完成的副本 给 b.js 模块。 然后 b.js 完成加载,并将 exports 对象提供给 a.js 模块。
简单的说就算,为了防止模块载入的死循环,Node.js在模块第一次载入后会把它的结果进行缓存,下一次再对它进行载入的时候会直接从缓存中取出结果,所以在这种循环依赖情形下,不会有死循环。
为什么不会无限循环引用分析
执行node main.js :
其它
虽然缓存解决了死循环的问题,但是大部分情况下我们不会这么写,而且这并没有解决正确导入模块的问题,所以,接下来看import,export📚。
参考
The text was updated successfully, but these errors were encountered: