0

I'm trying to clean up my code and implement es6 modules for the first time. I have created three module files and am using the import/export keyword where necessary and have specified type="module" in index.html.

The problem is everything functions correctly except all the global variables are undefined in my main file and now I get Reference Errors: Variable not defined if I try to console.log(variable)in the console. Confusing me further is if I place the same console.log(variable) inside an IIFE within the file it correctly displays the variable value with no Reference Error.

For example:

<script type="module">
  let foo = "some text";

  (function() {
    console.log(foo)
  }()); // prints "some text"

  console.log(foo); // prints Reference Error: foo not defined
</script>

Are there special rules for how global variables are handled in es6 modules? I'm just really confused because the everything else works properly and all I changed was splitting my file using es6 modules and running a local server (because of CORS error from using module pattern).

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
dumdum3000
  • 185
  • 1
  • 4
  • 12
  • 1
    Variables declared inside modules are not implicitly global (thankfully), so they're not referenceable outside unless deliberately exposed - but, the code you posted doesn't result in the error you describe – CertainPerformance Nov 02 '19 at 04:32
  • Your example doesn't throw an error? – Bergi Nov 02 '19 at 09:30
  • Yeah that's what's confusing me. On its own it works but it will throw an error when used within my file. Maybe stack overflow isn't the correct venue for this given it probably doesn't make sense unless someone can see my whole file. – dumdum3000 Nov 02 '19 at 15:46

1 Answers1

0

It appears my issue was a misunderstanding of how the console works and that it doesn't have access to a variable within a module file unless it is made global by attaching it to window.

For example, this now allows me to access the variable in question:

let foo = "some text";
window.foo = foo;

console.log(foo); // now prints "some text" in the console instead of Reference Error

Related answers:

How to access functions defined in es6 module in a browsers javascript console

What is the correct way to define global variable in ES6 modules?

dumdum3000
  • 185
  • 1
  • 4
  • 12