1

I'm learning about JS and I started my first project so I decided to keep it organized while divide my app.js in some files.

My problem is that when I start a module my console doesn't let me access document's variables, so I think the problem is in the scope, but I don't know why, I searched about scope and modules and I don't know what I'm doing wrong

The files are:

  • index.html
  • app.js
  • variables.js

HTML code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script src="app.js" type="module"></script>
    </body>
</html>

app.js code:

import { var1 } from "./variables.js";

console.log(var1);

variables.js code:

export const var1 = "var1";

In my console will appear console.log(var1) output as expected but if I try to type "console.log(var1)" or just call "var1" it will throw the following error: referenceError

PS: I use VSCode live server extension in order to use modules in vanilla js. PS: I know that I have to declare the variables in window scope but I thought I wasn't recommended, is there another way?

I expected to access variables, objects and functions in the console for debuggin purpose...

  • The code you execute in your console runs in the global scope. Variables declared in a module are scoped to that module only. Why are you trying to access variables in your console anyway? This smells like an [XY Problem](https://xyproblem.info/) – Phil Feb 08 '23 at 00:42
  • _"the console for debuggin purpose"_... use the actual debugger instead. You can locate lines of code to attach breakpoints in the _Sources_ tab or you can simply add [`debugger`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger) into your code – Phil Feb 08 '23 at 00:46
  • Ok, I didn't know about XY Problem so thank you, and I didn't know about debugger either... – Gabriel Pozzi Feb 09 '23 at 20:38

0 Answers0