I have two javascript functions defined in a normal <script>
tag and one imported within a <script type="module">
tag:
<script type="module">
import { mean } from "./node00.js";
console.log(mean(1,2,3)); // OK -- just to confirm this works fine
</script>
<script>
function xNew(x) { console.log("Calling xNew"); }
</script>
<span onclick="mean(1,2,3,4)">Hello</span>
<span onclick="xNew(5)">It's me.</span>
It seems that the mean
function within the module is not accessible to the html, whereas the xNew
function within the normal script tags is. What is the scoping and accessibility of these two items? And if module
makes the javascript hidden from the html what would be the point of using it?
CodePudding user response:
From the nature of module
, modules can talk to modules by import
and export
only (No communications outside of modules), but you can add events on DOM objects via document
or window
which is shared for all modules.
<script type="module">
function sum(a,b) {
console.log('Calling sum');
return a b;
}
document.getElementById("test-sum").onclick = () => sum(2,3)
</script>
<script>
function xNew(x) {
console.log("Calling xNew");}
</script>
<span id="test-sum">Hello</span>
<span onclick="xNew(2)">It's 'a me, mario</span>
CodePudding user response:
It seems a script tag having type="module"
attribute specifies that it to be considered as a Javascript module. It may be importing other Javascript module(s) inside it and becomes a "top-level" module for the imported modules.
For example:
// file "module.js"
export var someVar = "Some data";
export function someFunc() {
return " for output";
}
// this has no "export" prefixed hence cannot be used outside this module
function someOtherFunction() {
return 1;
}
<script type="module">
import {someVar, someFunc} from './module.js';
// "Some data for output"
console.log(someVar someFunc());
</script>
In the example above the module that is created is imported using the import statement.