简体   繁体   English

意外的令牌“导出”

[英]Unexpected token 'export'

I am trying to export variables from index.js to profile.js.我正在尝试将变量从 index.js 导出到 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但是,当我在 DOMContentLoaded 事件之后导出时,例如

document.addEventListener('DOMContentLoaded', function(){ export let k = 12; })

then it shows Unexpected token 'export' .然后它显示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我应该怎么做才能在 DOMContentLoaded 之后导出变量

You can't.你不能。 export and import can only appear at the top level of a module. exportimport只能出现在模块的顶层

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.如果其他模块导入k ,它们将获得一个只读绑定,这意味着如果它们在DOMContentLoaded之前使用它,它们将获得您提供的任何初始值(上面的undefined ,因为let k;声明中没有初始化器),但如果他们在DOMContentLoaded之后使用它,他们将看到处理程序分配的值。

That said, if your module provides information that is only available after a certain point, you might consider exporting a promise, like so:也就是说,如果您的模块提供的信息仅在某个时间点之后可用,您可以考虑导出 promise,如下所示:

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:或者在支持顶级await的环境中,如果导入模块在没有k的情况下无法做任何有用的事情,他们可以这样做:

import { kPromise } from "./your-module.js";
const k = await kPromise;
// ...use `k`...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM