ES6 的惯用揭示模块模式

Idiomatic Revealing Module Pattern for ES6

过去我用过revealing module pattern

function myModule() {
  function foo() ...
  function bar() ...

  return { 
    foo: foo, 
    bar: bar
  };
}

在 ES6 中,对象 shorthand 得到了改进。

function myModule() {
  function foo() ...
  function bar() ...

  return { foo, bar };
}

现在使用内置模块语法,我正在努力寻找与上述最相似的首选模式。

选项 #1 名为 exports

// export file
function foo() ...
function bar() ...

export { foo, bar };

// import file
import { foo, bar } from './export-file';

foo();
bar();

选项 #2 默认 export/import 解构

// export file
function foo() ...
function bar() ...

export default { foo, bar };

// import file
import baz from './export-file';

const { foo, bar } = baz;

foo();
bar();

选项 #3 默认 export/import,名称间距

// export file
function foo() ...
function bar() ...

export default { foo, bar };

//import file
import baz from './export-file';

baz.foo();
baz.bar();

我喜欢带有命名导出的选项 #1,因为它在 "destructuring" 导入语法中提供了简单性。

import { foo, bar } from './export-file';

我还想继续使模块的导出 API 在导出对象中的导出文件底部明确定义。

export { foo, bar };
// OR
export default { foo, bar };

我一直读到默认导出是首选,所以我一直在尝试找到包含默认导出的首选模式,但我不愿意采用,因为它看起来更冗长且没有什么优点(除了需要名称间距,或者在某些情况下同时包含命名和默认导出之外)。

是否有 ES6 模块语法的揭示模块模式的惯用模式?

I read all the time that default exports are preferred

不,他们不是。它们更简单,语法更短,可能会更频繁地使用(因为有更多的小型单导出模块),但它们通常不是首选。

使用正确的工具来完成工作。您已经知道您想要的优势。

Is there an idiomatic pattern for the revealing module pattern with ES6 module syntax?

是的,选项 #1。当你有多个东西要导出时,总是使用命名导出。

你会从挑剔的语法中得到明确的别名和摇树

import { foo, bar } from './export-file';

以及命名空间

import * as baz from './export-file';