2

I'm having a problem with modules/scope. I need to declare script tags as type="module" but then functions declared in that scope are not global, so can't be called with onload etc.

First file: index.html

<html>
<head>

<script type="module">
  import {sayHi} from './sayHi.js';
  function x() {
    var myDiv = document.getElementById('myDiv');
    myDiv.innerHTML = sayHi('John')
  }
</script>

</head>
<body onload="x()">
  <div id="myDiv"> *** replace with function call *** </div>
</body>
</html>

Second file: sayHi.js

export function sayHi(user) {
  return (`Hello, ${user}!`);
}

The x function is not in scope outside of the block, so I get the error:

(index):36 Uncaught ReferenceError: x is not defined
    at onload ((index):36)

How do I make x global?

2 Answers 2

3

While it's possible to create global variables from a module script, there is likely no need for this in your situation.

Since the evaluation of module scripts is automatically deferred, you can directly access the element in the script:

<script type="module">
  import {sayHi} from './sayHi.js';
  var myDiv = document.getElementById('myDiv');
  myDiv.innerHTML = sayHi('John')
</script>

If this doesn't work for you for whatever reason, bind an event handler from inside the script instead:

<script type="module">
  import {sayHi} from './sayHi.js';
  window.addEventListener('DOMContentLoaded', () => {
   var myDiv = document.getElementById('myDiv');
   myDiv.innerHTML = sayHi('John')
  });
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

It seems like that's how modules work: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

Last but not least, let's make this clear — module features are imported into the scope of a single script — they aren't available in the global scope. Therefore, you will only be able to access imported features in the script they are imported into, and you won't be able to access them from the JavaScript console, for example. You'll still get syntax errors shown in the DevTools, but you'll not be able to use some of the debugging techniques you might have expected to use.

But this SO post should provide you with a workaround:

<html>
<head>

<script type="module">
  import {sayHi} from './sayHi.js';
  function x() {
    var myDiv = document.getElementById('myDiv');
    myDiv.innerHTML = sayHi('John')
  }
  document.addEventListener("DOMContentLoaded", x);
</script>

</head>
<body>
  <div id="myDiv"> *** replace with function call *** </div>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.