【问题标题】:How was I able to change imported value in ES6?我如何在 ES6 中更改导入的值?
【发布时间】:2019-05-29 21:56:01
【问题描述】:
//lib-es6.js

export let counter = 3;
export function incCounter() {
  counter++;
}

来自16.7.2 section,即使我们通过星号 (*) 导入模块,导入的值也不能更改。

//main-es6.js

import * as lib from './lib-es6'; // imported via asterisk(*)

// The imported value `counter` is live
console.log(lib.counter); // 3 . => I expected this
lib.incCounter();
console.log(lib.counter); // 4 . => I expected this

/****************************************/ 
// But I was able to change lib.counter.
// Question: Can we change imported value in ES6 if we import it via asterisk (*)?
lib.counter++; // Not an error. ==> I DID NOT expected this.
console.log(lib.counter); // 5
/****************************************/    

【问题讨论】:

  • 我的猜测:lib 指的是具有counter 属性的对象,并且该属性不是不可变的。
  • 你是直接在 node 中运行代码(在那种情况下是哪个版本)还是先通过 babel 之类的东西编译它?
  • @Markus-ipse 是的,我使用的是 babel7,node10。我正在使用 "@babel/core": "^7.4.5", "@babel/node": "^7.4.5"
  • 看起来你的转译器没有发现这个错误。这可能取决于 babel 选项,但 .counter 应该是没有 setter 的 getter。

标签: ecmascript-6 es6-modules es6-module-loader


【解决方案1】:

您并没有真正执行 ES 模块,您正在执行 CommonJS 模块(从 ES 模块转译而来)。如果您在本机运行此代码,您应该会得到预期的结果:

【讨论】:

  • 嗨@Axel 1。我用--experimental-modules 尝试了node.js 12。它仍然无法解析 lib-es6。 2. 如何在不使用 babel 捆绑的情况下在浏览器中运行?任何 jsfiddle 链接都有助于参考。 3. 我尝试使用 [yarn add esm] 运行,[node -r esm main-es6.js] 仍然是相同的输出。没有错误。
  • 嗨@Axel,如果我正在执行CommonJS 模块,那么当我执行counter++ 时,为什么不合格的导入工作正常并按预期抛出错误。如果在我增加本地副本时它是 commonJS 正确,它不应该抛出错误?
  • 探索 ES 模块的最佳方式是以纯粹的形式使用它们,无需任何转译。如果您转译,您唯一的选择就是查看转译后的代码。
猜你喜欢
  • 2018-06-18
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 2018-11-12
  • 2017-01-31
  • 1970-01-01
相关资源
最近更新 更多