实现 es6 模块后出现变量引用错误

Getting variable reference errors after implementing es6 modules

我正在尝试清理我的代码并第一次实现 es6 模块。我创建了三个模块文件,并在必要时使用 import/export 关键字,并在 index.html 中指定了 type="module"

问题是除了所有全局变量在我的主文件中都未定义外,所有功能都正常运行,现在如果我尝试在控制台中 console.log(variable),我会得到 Reference Errors: Variable not defined。更让我困惑的是,如果我将相同的 console.log(variable) 放在文件的 IIFE 中,它会正确显示变量值而没有引用错误。

例如:

<script type="module">
  let foo = "some text";

  (function() {
    console.log(foo)
  }()); // prints "some text"

  console.log(foo); // prints Reference Error: foo not defined
</script>

es6模块中全局变量的处理方式有特殊规定吗?我只是真的很困惑,因为其他一切都正常工作,我所做的只是使用 es6 模块和 运行 本地服务器拆分我的文件(因为使用模块模式导致 CORS 错误)。

看来我的问题是对控制台工作方式的误解,它无法访问模块文件中的变量,除非通过将其附加到 window.[=14 使其成为全局变量。 =]

例如,这现在允许我访问有问题的变量:

let foo = "some text";
window.foo = foo;

console.log(foo); // now prints "some text" in the console instead of Reference Error

相关回答:

What is the correct way to define global variable in ES6 modules?