Charlie lee
Charlie lee

Reputation: 71

Question about importing js module and function scope(local/global)

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..

Upvotes: 5

Views: 1759

Answers (1)

leisheng
leisheng

Reputation: 382

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!

Upvotes: 3

Related Questions