调试使用 ES6 模块的 JavaScript 代码

Debugging JavaScript code that uses ES6 Modules

TL;DR:如何从调试器访问 ES 模块中定义的 variables/functions/names?

更多上下文:我是一个相对有经验的 JavaScript 程序员,但对模块不熟悉。我在这里遵循了 MDN 上的教程:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules. They have a good set of examples here: https://github.com/mdn/js-examples/tree/master/modules

在该集合中,在“基本模块”示例中,(此处的实时代码:https://mdn.github.io/js-examples/modules/basic-modules/)例如,文件 [=12] 中有一个名为 random 的函数=].假设我想在调试器中执行该函数,只是为了尝试一下,或者因为这是我的代码并且我想 test/debug 它,或者我想向另一个编码器演示该函数的作用。您希望在 REPL 或调试器中执行的所有操作。有没有办法做到这一点?我已经尝试了 Firefox 调试器和 Chrome 调试器,但没有成功。

回到前模块时代,该代码将被放入全局命名空间(使访问变得容易)或者它会被锁定在一个 IIFE 中(使访问变得不可能)或者可能在一些自制的模块系统中(访问取决于)。我希望新的模块系统仍然允许调试器访问模块内的名称。

谢谢。

它说 in the docs:

Last but not least, let's make this clear — module features are imported into the scope of a single script — they aren't available in the global scope. Therefore, you will only be able to access imported features in the script they are imported into, and you won't be able to access them from the JavaScript console, for example. You'll still get syntax errors shown in the DevTools, but you'll not be able to use some of the debugging techniques you might have expected to use.

以您之前的示例为例,您需要从它可见的范围调用该函数,即它被导入的范围:

import { random } from 'path/to/square.js'

debugger; // you should be able to invoke random() from here