Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export function to window namespace from javascript module

I understand that one of the characteristics/goals of modules is that variables/functions defined inside are not accessible from the outside the script. However, if I want to export one specific function to be used globally, how would I do that? Just assigning to the window as I have read in other posts doesn't seem to work:

in index.html

<script type="module">
   const add = (a, b) => a + b;
   window.add = add;
</script>
<script>
   console.log(window.add(1, 2));
</script>

Results in Uncaught TypeError: window.add is not a function

like image 827
phoebus Avatar asked Oct 20 '25 00:10

phoebus


1 Answers

This is because the "module" script is being interpreted second. Adding a console log verifies this.

<script type="module">
  var add = (a, b) => a + b;
  window.add = add;
  console.log("This prints second:", window.add)
</script>

<script>
  console.log("This prints first:", window.add)
  console.log(window.add(1, 3));
</script>
like image 197
Raed Avatar answered Oct 22 '25 16:10

Raed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!