I have some strange behavior in my javascript front end code so I am asking a going back to basics question. First I will setup some examples.
script1.js
var script1Var = "script variable";
function script1Test(){
console.log("hello from script1 test");
}
script2.js
function script2Test(){
console.log("hello from script2 test");
}
module1.js
export default function module1Test(){
console.log("hello from module1 test");
}
module2.js
export default function module2Test(){
console.log("hello from module2 test");
}
test_page1.html
<html>
<head>
<script src="script1.js"></script>
<script src="script2.js"></script>
</head>
</html>
test_page2.html
<html>
<head>
<script type="module" src="module1.js"></script>
<script type="module" src="module2.js"></script>
<script src="script1.js"></script>
<script src="script2.js"></script>
</head>
</html>
Here are my questions:
- During runtime because of how
test_page1.htmlis laid out I presume thatscript2.jscan call functions inscript1.jswithout the need of any imports, but canscript1.jscall functions inscript2.js? Basically does order matter? I am quite positive that it does. - In
test_page2.htmlare functions frommodule1.jsandmodule2.jsvisible toscript1.jsandscript2.js? If not, how can they be made visible to them? - In
test_page2.htmlare functions frommodule1.jsvisible tomodule2.jswithout the use of imports?
Basically my questions boil down to, how can a classic script (does not have exports in it) be used in modules? And how can modules be used in classic scripts. Converting the classic script into a module is not an option here since there is a lot of code that depends on using it as a classic script. And the same for modules, they can not be converted to classic scripts since there is other code using them as modules.
thank you for your help
It depends.
script1.jscannot call functions fromscript2.jswhile its being evaluated. I.e. something likewouldn't work.
But it can call those functions as long as it is after
script2.jsloaded. For example in response to an event:No. Each module creates a separate scope. Exports can only be accessed by importing them.
The modules would have to explicitly create global variables, e.g. by assigning a property to
window:But also here, such a function would only be callable after the module loaded/was evaluated.
The better solution (at least I believe this works in "normal" scripts) would be to import the module dynamically, via the
importfunction:No. As I said, every module creates its own scope.