5

Hi I'm new in js and I'm trying to understand local/global scope when importing js module.

Below is my html/js file which is working.

enter image description here

Below is my html/js file which is not working.

enter image description here

Please tell me the reason why I have to put document.querySelector~~~ and why the second one doesn't work..

Dan Bonachea
  • 2,408
  • 5
  • 16
  • 31
  • I hope this helps: [Use functions defined in ES6 module directly in html](https://stackoverflow.com/q/53630310/12695621) – Mubaraq Wahab Jun 11 '20 at 00:23

1 Answers1

3

Your main.js should be:

import {make_black} from "/static/sub.js";

window.make_black = make_black;

When you import an external script as a module using script tags, the module code is run but exports are not accessible in anyway. You have to explicitly add them to the window, like in the example above. Then you will be able to access make_black inside your html onclick attribute.

If you wanted to export something from a module, for example:

main.js

import {make_black} from "/static/sub.js";

export let mb = make_black;

and then access your mb function inside your main.html, you would have to do something like this:

main.html

<script type="module">
    import {mb} from "/static/main.js";
    // now you can use mb here, which is a reference to your make_black function
    // inside sub.js
</script>

If you just import an external script as a module, there is no way to access its variables in its scope. You have to either import them inside script tags with type="module" (as shown above) or explicitly make them available by assigning them to the window inside your js file (also as shown above). It's a little confusing the way that modules work in the browser!

leisheng
  • 340
  • 1
  • 8
  • you mean that when I import function from module, I can't use that function if I didn't make it global scope? Please see the another file which I add now – Charlie lee Jun 11 '20 at 00:43
  • Yes. In the case of your new file you added, you would have to change export function brother(){...} to window.brother = function() {...} for it to work correctly. The way that ES6 modules work when you import them via script tags is more than a little counter-intuitive. So much so that I have made my own library to use in my code which mimics Python's import syntax. – leisheng Jun 11 '20 at 00:53
  • 1
    Thank you very much. I understand about how to import js module. – Charlie lee Jun 11 '20 at 00:54