javascript - 调试使用 ES6 模块的 JavaScript 代码

标签 javascript debugging module names inspect

TL;DR:如何从调试器访问 ES 模块中定义的变量/函数/名称?

更多背景信息:我是一名相对经验丰富的 JavaScript 程序员,但对模块不熟悉。我在这里遵循了 MDN 上的教程:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules .他们在这里有一组很好的例子:https://github.com/mdn/js-examples/tree/master/modules

在那个集合中,比如在“基本模块”示例中,(此处的实时代码:https://mdn.github.io/js-examples/modules/basic-modules/)例如,文件 modules 中有一个名为 random 的函数/square.js。假设我想在调试器中执行该函数,只是为了尝试一下,或者因为这是我的代码并且我想测试/调试它,或者我想向另一个编码器演示该函数的作用。您希望在 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

关于javascript - 调试使用 ES6 模块的 JavaScript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62763721/

相关文章:

java - 设置Java的登录系统和权限

java - NetBeans 语言支持 : CTRL-S doesn't save text file changes

javascript - _destroy() 还是 destroy()?

javascript - 删除 html 页面的可打印版本上的输入占位符

javascript - Node.js 流可读.read 重复调用

delphi - 填充监 window 口中的所有字段值

javascript - 如果使用 row.add,ng-click 无法与 AngularJS 和 jquery dataTables 一起使用

debugging - 无法在 Chrome 开发工具中设置断点,版本 26.0.1410.64 m

javascript - 如何使用IntelliJ IDEA调试器调试Nashorn JavaScript?

python - 确定给定的 Python 模块是否为内置模块