I have a project built using Javascript, jQuery, and Vite.js. I need to share functions and variables between one JS file that is a module, and another JS file that is not a module. I'm specifically talking about whether the script tag has type="module"
or not. Is this possible? I understand that if I could just set both script file types to "module", this would solve my problem and I could easily just use import/export syntax to share functions and variables. However, the 2nd script cannot be set to type="module"
, as that would break snippets of code using certain dependencies.
Just to illustrate what I'm saying -- here's an HTML file linked to two different JS files:
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script type="module" src="./script1"></script>
<script src="./script2"></script>
</head>
<body></body>
</html>
Now, script1.js
has a variable we want to access from script2.js
:
script1.JS
const testVariable = "hello test variable";
script2.js
console.log(testVariable) //returns undefined
Obviously I can't use import/export or require since the 2nd script is not a module. Is there any way around this? I know that normally script files can access functions from script tags placed above them, but this doesn't seem to hold true for two different script types.
I thought maybe I could use jQuery $.getScript
per this S/O post, but as far as I can tell, that executes the requested script, but doesn't allow me to dynamically access specific variables and/or functions in the requested script?