Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

javascript - How can an es6 module import itself?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  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)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...