我有一个名为 fooModule 的模块。在本模块中,我导入 fooModule (本身):
import *作为fooModule从'./fooModule'; 导出函数logFoo(){ console.log(fooModule)}当调用 logFoo()时,我可以看到fooModule的所有导出。 这是如何工作的?
解决方案循环依赖对于声明性导入/导出没有问题。在你的情况下,圆圈的最小长度是: - )
解决方案是, import 将值导入到变量中,但是它将一个变量引用导出到导出的变量中。有关可变变量的示例,请查看此处,并在这个问题用于确切的术语。 它对于模块命名空间对象是一样的 - 它们的属性只是解析为实际导出变量的getter。 >
所以当你的模块被加载和评估时,会出现以下步骤:
现在当你在一个模块中调用 logFoo 导入它, fooModule 将引用包含 logFoo 的命名空间。没有魔法: - )
I have a module called fooModule. Inside this module, I import fooModule (itself):
import * as fooModule from './fooModule'; export function logFoo() { console.log(fooModule) }When logFoo() is called, I can see all of the exports of the fooModule. How does this work?
解决方案Circular dependencies are no problem for declarative imports/exports. In your case, the circle is of minimal length though :-)
The solution is that an import does not import a value into a variable, but that it makes a variable a reference to the exported variable. Have a look here for an example of a mutable variable, and at this question for exact terminology. And it's the same for module namespace objects - their properties are just getters that resolve to the actual exported variable.
So when your module is loaded and evaluated, the following steps occur:
Now when you call logFoo in a module that imports it, fooModule will refer to the namespace that contains logFoo. No magic :-)
更多推荐
es6模块如何导入?
发布评论