ES6中如何导入匿名函数

mav*_*ick 1 javascript ecmascript-6

在 ES6 中,我们可以像这样导入导出的模块:

import { Abc } from './file-1';  // here Abc is a named export
import Def from './file-2';  // here Def is the default export
Run Code Online (Sandbox Code Playgroud)

但是我们如何导入匿名函数呢?考虑这段代码:

文件-3.js:

export function() {
  return 'Hello';
}

export function() {
  return 'How are you doing?';
}
Run Code Online (Sandbox Code Playgroud)

鉴于上述两个函数既不是默认导出也不是命名导出(匿名函数没有名称!),如何将它们导入到另一个文件中?

Est*_*ask 5

单个匿名函数可以导出为default(默认导出值可以是任何值)。多个匿名函数无法从模块中导出 - 因此它们也无法导入。

export语句遵循严格的语法,支持命名或默认导出。这将导致语法错误:

export function() {
  return 'Hello';
}
Run Code Online (Sandbox Code Playgroud)

这些函数应命名为导出:

export const foo = function () {
  return 'Hello';
}

export const bar = function () {
  return 'How are you doing?';
}
Run Code Online (Sandbox Code Playgroud)

因此它们可以以相同的名称导入。