Let's assume that you have the following index.html
:
html<!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>Hello, world</title> </head> <body> <p>Hello, world</p> <script src = "./one.js" type = "module"></script> <script src = "./two.js" type = "module"></script> </body> </html>
As scripts have type = "module"
, if you declare a variable on one.js
:
javascriptvar x = 20;
And you try to access it on two.js
:
javascriptconsole.log(x); // undefined
You can solve it by declaring the variable as a window variable on one.js
:
javascriptwindow.x = 20;
Then, on two.js
:
javascriptconsole.log(x); // 20
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.