3

I am curious as to why I do not have access to defined variables in the browser console when I have my script type set to type="module".

Below is a hypothetical set up:

<!DOCTYPE html>
<html>
<head>
  <div id="containerFirst">...</div>
  <div id="differentContainer">...</div>
</head>

<body>
  ...
</body>
<script type="module" src="module.js"></script>
<script src="normal.js"></script>
</html>

And here are the two JS files, first module.js:

export const firstContainer = document.getElementById('containerFirst');

and similar variable structure in normal.js:

const otherContainer = document.getElementById('differentContainer');

When I run this in a browser, I can access the variable defined in normal.js by typing it directly into the console but not the one from module.js. I'm hoping to find some clarity on this matter. Thanks!

Asad ali
  • 147
  • 2
  • 11
ricardoom
  • 71
  • 1
  • 9
  • 2
    modules are encapsulated in their own namespace. – ASDFGerte Jan 14 '20 at 15:48
  • Does this answer your question? [How can I use modules in the browser, but also refer to variables and functions from within DevTools?](https://stackoverflow.com/questions/58679410/how-can-i-use-modules-in-the-browser-but-also-refer-to-variables-and-functions) – cachius May 07 '22 at 15:39

1 Answers1

4

You'd be able to access the module variables if you were paused on a breakpoint in the relevant module's code, but not if you aren't. Top-level declarations in modules aren't globals, by design. Each module gets its own scope, kind of like they're a function that gets called just once (that's a rough analogy), so top-level declarations are private to the module's scope (unless you export them, of course).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875