es6 模块如何导入自身? [英] How can an es6 module import itself?

查看:39
本文介绍了es6 模块如何导入自身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 fooModule 的模块.在这个模块中,我导入 fooModule(本身):

I have a module called fooModule. Inside this module, I import fooModule (itself):

import * as fooModule from './fooModule';

export function logFoo() {
  console.log(fooModule)
}

logFoo() 被调用时,我可以看到 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 :-)

解决方案是 import 不会将值导入到变量中,而是使变量成为对导出变量的 引用.查看此处的可变变量示例,以及这个问题 了解确切的术语.
模块命名空间对象也是如此——它们的属性只是解析为实际导出变量的 getter.

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:

  1. exportimport 声明的源进行静态分析以构建依赖图
  2. 模块作用域已创建
  3. 因为你的模块唯一的依赖是它自己,而且它已经被初始化,它不需要等待
  4. fooModule 变量被创建并实例化为一个对象,该对象具有模块的导出名称,已知为 ["logFoo"].fooModule.logFoo 属性成为一个 getter,它将计算模块范围内的 logFoo 变量(如果您使用了 export {A as B},然后 fooModule.B 将解析为 A,但在您的情况下,两个名称相同).
  5. 模块范围内的变量声明创建变量,在您的情况下为 logFoo,并且函数声明被初始化(即 logFoo 被分配了函数)
  6. 模块代码已运行(在您的情况下,没有任何反应)
  1. The source is statically analysed for export and import declarations to build a dependency graph
  2. The module scope is created
  3. Since the only dependency of your module is itself, and that already is getting initialised, it doesn't need to wait for it
  4. The fooModule variable is created and instantiated to an object with the exported names of the module, which are known to be ["logFoo"]. The fooModule.logFoo property becomes a getter that will evaluate to the logFoo variable in the module scope (if you had used export {A as B}, then fooModule.B would resolve to A, but in your case both names are the same).
  5. The variable declarations in the module scope create the variables, in your case logFoo, and function declarations are initialised (i.e. logFoo gets assigned the function)
  6. The module code is run (in your case, nothing happens)

现在,当您在导入它的模块中调用 logFoo 时,fooModule 将引用包含 logFoo 的命名空间.没有魔法:-)

Now when you call logFoo in a module that imports it, fooModule will refer to the namespace that contains logFoo. No magic :-)

这篇关于es6 模块如何导入自身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆