Module Scoping JS

22 Views Asked by At

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

0

There are 0 best solutions below