4

TL;DR: How can I access variables/functions/names that are defined in ES Modules from the debugger?

More context: I'm a relatively experienced JavaScript programmer, but new to Modules. I've followed the tutorial at MDN here: 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

In that collection, say in the "basic-modules" example, (live code here: https://mdn.github.io/js-examples/modules/basic-modules/) there is, for example, a function called random in the file modules/square.js. Suppose I want to execute that function in the debugger, just to try it out, or because it's my code and I want to test/debug it, or I want to demonstrate to another coder what the function does. All the stuff you expect to do in a REPL or debugger. Is there a way to do that? I've tried both the Firefox debugger and the Chrome debugger, with no luck.

Back in the pre-Modules era, that code would be put into the global namespace (making access easy) or it would be locked up in an IIFE (making access impossible) or maybe in some home-made module system (access depends). I am hoping that the new Modules system still allows the debugger access to the names inside modules.

Thanks.

  • Did you try the https://marketplace.visualstudio.com/items?itemName=ms-vscode.js-debug extension in VsCode? No need to write "debugger;" in your code anymore, just setup your launch.json file, place a breakpoint on the side like any usual IDE, and you should be able to debug javascript modules – Pursuable Jul 06 '20 at 22:59

1 Answers1

0

It says 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.

To take your example from before, you'll need to invoke that function from a scope where it is visible, i.e where it's been imported:

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

debugger; // you should be able to invoke random() from here
Renaud
  • 4,569
  • 7
  • 41
  • 72
  • there are alternatives listed [here](https://stackoverflow.com/questions/52569996/how-to-use-es6-modules-from-dev-tools-console) – Renaud Nov 08 '20 at 10:01
  • Thanks @Renaud. I had read that in the Docs, but I was hoping for better. The alternative that you listed was helpful. – Scott Anderson Nov 10 '20 at 19:16