如何导出 es6 IIFE?

Bil*_*oel 0 javascript iife es6-modules

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 };
Run Code Online (Sandbox Code Playgroud)

上面的代码运行得很好,但是当我将其重构为下面的代码时,我收到一个 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 };
Run Code Online (Sandbox Code Playgroud)

我是否需要加载程序或者有特殊的方法来导出这些类型的函数?

Cer*_*nce 5

由于您想要默认导出,因此可以将整个内容放在export default. 由于您还希望能够引用该函数并调用它,因此除了导出它之外,如果您确实想走 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;
})();
Run Code Online (Sandbox Code Playgroud)

但是 ES6 模块中不需要 IIFE - 无论如何,模块的顶层范围仅限于模块。在您的第一个代码片段中,没有任何内容泄漏到全局范围内,并且发生的情况更清楚,因此您可能更喜欢它。

IIFE 在模块之外很有用,因为在顶层定义某些内容会污染全局范围,但在模块中则不必担心。模块内部唯一的全局变量是那些您显式分配给的变量window(或者无论全局对象是什么),这里没有这样做。