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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With