【问题标题】:Understanding code execution with ES6 modules理解 ES6 模块的代码执行
【发布时间】:2018-11-06 05:01:05
【问题描述】:

问题在底部提到

在我的 React 生产构建中,我使用 Webpack 已经有一段时间了。

我对 ES6 模块感兴趣,关于代码分离和执行。

所以我想出了以下测试代码来了解模块的行为。

代码放在 src 文件夹中。 Webpack 打包代码,然后 bundle.js 在终端中使用 node ./dist/bundle.js 运行

代码:

./src/index.js

import node1 from "./node1";   
import node2 from "./node2";

function part() {
  node1();
  node2();
}

part();

./src/node1.js

import test, { x } from "./test";

function node1() {
  console.log("node1", x, new Date().getTime());
  test();
  console.log("node1", x, new Date().getTime());
}

export default node1;

./src/node2.js

import test, { x } from "./test";

function node2() {
  console.log("node2", x, new Date().getTime());
  test();
  console.log("node2", x, new Date().getTime());
}

export default node2;

./src/test.js

let x = 1;
console.log(x, new Date().getTime());

function test() {
 console.log(
  "This is test for understanding dependency graph",
  x++,
  new Date().getTime()
 );
}

export default test;

export { x };

执行结果

问题:我希望x 的导出值保持不变。为什么是 不是吗?

问题:运行时显示的行为是因为webpack 捆绑还是import\export ES6 模块规范的更多固有部分?

【问题讨论】:

  • test() 函数显式递增时,为什么您希望x 保持不变?
  • 所以我试图理解行为,模块对变量进行范围界定。我一直期望x 的导出值保持不变,因为test 是在范围内定义的,因此由于关闭,它应该可以访问该变量。我所问的很有可能是完全错误的,但我无法理解导入和导出。
  • 我希望我的导出是静态的

标签: javascript node.js webpack import ecmascript-6


【解决方案1】:
  1. 在 ES6 模块中,导出值不是真正的值,而是不可变的绑定。简单地将x 放入node1.j 是对x 的不可变引用test.js
  2. 由 ES6 模块设计

您可以在这里阅读更多内容:http://2ality.com/2015/07/es6-module-exports.html

【讨论】:

  • immutable reference 作为一个术语解释了整个行为
猜你喜欢
  • 2017-10-20
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多