[英]How do i export an es6 IIFE?
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 };
上面的代碼工作得很好,但是當我將它重構為下面的代碼時,我得到一個 eslint 錯誤,說Parsing error: Export 'renderTask' is not defined。 .
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 };
我需要一個加載器還是有一種特殊的方法來導出這些函數?
由於您需要默認導出,因此可以將整個內容放在export default
之后。 由於您還希望能夠引用 function 並調用它,除了導出它之外,如果您真的想要 go 的 IIFE 路由,在 IIFE 內部定義它,調用它,然后返回它。
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 - 模塊的頂層無論如何都只限於該模塊。 在您的第一個片段中,沒有任何東西泄漏到全局 scope 中,而且發生的事情更清楚,所以您可能更喜歡它。
IIFE 在模塊之外很有用,當在頂層定義一些東西會污染全局 scope 時,但在模塊中你不必擔心。 模塊內部唯一的全局變量是您明確分配給window
(或全局 object 的任何變量)的變量,此處未完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.