es6 import as a read only view understanding

孤人 提交于 2019-12-04 04:42:05

See section 16.3.5 here

As mentioned:

The imports of an ES6 module are read-only views on the exported entities. That means that the connections to variables declared inside module bodies remain live, as demonstrated in the following code.

//------ lib.js ------
export let counter = 3;
export function incCounter() {
    counter++;
}

//------ main.js ------
import { counter, incCounter } from './lib';

// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4

How that works under the hood is explained in a later section.

Imports as views have the following advantages:

  • They enable cyclic dependencies, even for unqualified imports.
  • Qualified and unqualified imports work the same way (they are both indirections).
  • You can split code into multiple modules and it will continue to work (as long as you don’t try to change the values of imports).

The answer depends on what is your entry module. For example, if you define an entry module as:

// index.js
import "./main1";
import "./main2";

Then the output is:

1 // from main1
2 // from main1
2 // from main2

ES6 modules are allowed hold state, but are not allowed to manipulate others modules state directly. The module itself can expose a modifier function (like your increment method).

If you want to experiment a bit, rollupjs has a nice online demo that shows how the standard imports and exports should work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!