const renderTask = (task) => {
if (task) {
const li = `<div class="li"><span><input type="checkbox">${task.description}</span><svg height="15" width="15" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z" />
</svg></div>`;
ul.innerHTML += li;
}
};
renderTask();
export { renderTask as default };
上面的代码工作得很好,但是当我将它重构到下面的代码时,我会得到一个省略错误,上面写着解析错误:导出'renderTask‘是没有定义的.。
const ul = document.querySelector('.ul');
(renderTask = (task) => {
if (task) {
const li = `<div class="li"><span><input type="checkbox">${task.description}</span><svg height="15" width="15" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z" />
</svg></div>`;
ul.innerHTML += li;
}
})();
export { renderTask as default };
我需要一个加载程序,还是有一种特殊的方法来导出这类功能?
发布于 2022-01-12 05:07:53
因为您想要一个默认的导出,所以可以将整个过程放在export default
之后。因为您还希望能够引用函数并调用它,除了导出函数之外,如果您真的想要走生命之路,在生命周期中定义它,调用它,并返回它。
export default (() => {
const renderTask = (task) => {
if (task) {
const li = `<div class="li"><span><input type="checkbox">${task.description}</span><svg height="15" width="15" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z" />
</svg></div>`;
ul.innerHTML += li;
}
};
renderTask();
return renderTask;
})();
但是不需要在ES6模块中使用生命周期--模块的顶层只是限定在模块上。在您的第一个片段中,没有任何东西泄漏到全局范围中,而且更清楚发生了什么,所以您可能会更喜欢它。
IIFE在模块之外是有用的,当在顶层定义某些东西时会污染全局范围,但是在模块中它并不是您需要担心的事情。模块中唯一的全局变量是那些显式分配给window
(或全局对象是什么)的变量,这里没有这样做。
https://stackoverflow.com/questions/70676535
复制相似问题