3

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?

Jack Bashford
44.3k11 gold badges56 silver badges84 bronze badges
asked Apr 13, 2019 at 8:23

2 Answers 2

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>
answered Apr 13, 2019 at 8:30
Sign up to request clarification or add additional context in comments.

Comments

2

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)

answered Apr 13, 2019 at 8:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.