I am trying to export variables from index.js to profile.js. When I export at the top of the file such as
export let k = 12;
Or
export { k }; let k = 12;
It works just fine. However, when I export after the DOMContentLoaded event such as
document.addEventListener('DOMContentLoaded', function(){ export let k = 12; })
then it shows Unexpected token 'export' . The one bellow is also gives the same error
if (true){ export let k = 2; }
What did I do wrong here?
What should I do to be able to export variable after DOMContentLoaded
You can't. export
and import
can only appear at the top level of a module.
What you can do instead is export the variable, and set its value in the handler:
export let k;
document.addEventListener('DOMContentLoaded', function(){ k = 12; })
If other modules import k
, they get a read-only binding to it, meaning that if they use it before DOMContentLoaded
, they'll get whatever initial value you provide ( undefined
in the above, because there's no initializer on the let k;
declaration), but if they use it after the DOMContentLoaded
, they'll see the value assigned by the handler.
That said, if your module provides information that is only available after a certain point, you might consider exporting a promise, like so:
let kPromiseResolve;
export const kPromise = new Promise(resolve => {
kPromiseResolve = resolve;
});
document.addEventListener('DOMContentLoaded', function(){ kPromiseResolve(12); })
Then modules using it would do:
import { kPromise } from "./your-module.js";
kPromise
.then(k => {
// ...use `k`...
})
.catch(error => {
// ...
});
or in environments supporting top-level await
, if the importing module can't do anything useful without k
, they could do:
import { kPromise } from "./your-module.js";
const k = await kPromise;
// ...use `k`...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.