I have JS file import.js (simplified):
let foo;
function fooBar () {
foo = bar;
}
window.onload = () => {
fooBar()
}
In my html file I have:
<script src=import.js type=module></script>
When I open the html file, at the console:
foo;
ReferenceError: foo is not defined
I understand that this is due to imported modules only given lexical scoping - but what is the best way to allow imported let
/const variables scope on the window/global, so that I can access it at the the window console?
2 Answers 2
Remove type="module" and it works. You weren't exporting anything, but you were treating import.js as something which exported a module. Just use it as you would any other script:
<script src="import.js"></script>
Comments
Because you're using <script type="module">, you can use import and export syntax, and transfer what you need, for example:
<script type="module">
import obj from './import.js';
// do stuff with obj.foo
</script>
while import.js exports an object to which you assign a foo property:
const exportObj = {};
function fooBar () {
exportObj.foo = bar;
}
window.onload = () => {
fooBar()
}
export default exportObj;
That said, since it's populated asynchoronusly, you might consider exporting a Promise instead:
<script type="module">
import fooProm from './import.js';
fooProm.then((foo) => {
// do stuff with foo
});
</script>
and
let foo;
function fooBar () {
foo = bar;
}
export default new Promise((resolve) => {
window.onload = () => {
fooBar();
resolve(foo);
}
});
(though, ideally, foo wouldn't get reassigned at all in the lower code)