无法在 Babel 中使用 es6 `export Module from 'file'`

Unable to use es6 `export Module from 'file'` in Babel

我正在使用 ES6 构建用于 JavaScript 与服务器通信的库。服务器具有通过 WebSocket 发送和接收的特定类型的 JSON-encoded 消息。

为确保包含所有消息字段并且不向服务器发送额外字段,每种消息类型都有自己的 class。每条消息都在其自己的文件中定义,结构如下:

export default class NameOfMessage extends BaseMessage {
    constructor(values) {
        // Here is code that checks values and sets them as properties
        // so that calling `JSON.stringify(obj)` will return the data
        // to be sent to the server.
    }
}

如果用户在特定文件中只需要一种或两种消息类型,他们可以写import NameOfMessageType1 from 'package_name/messages/type1'import NameOfMessageType2 from 'package_name/messages/type2'

但是,如果用户需要多种消息类型,则将它们全部包括在内会变得很麻烦。为此,我创建了一个附加文件 messages.js,其中 import 包含所有消息文件,然后重新 export 包含它们。这样,用户可以执行 import * as Message from 'package_name/messages' 并访问 Message.Type1Message.Type2 等消息类型

根据我的阅读,(包括 http://www.2ality.com/2014/09/es6-modules-final.html and https://hacks.mozilla.org/2015/08/es6-in-depth-modules/(标题为 "Aggregating modules" 的部分)以及其他来源),我应该能够使用以下内容作为 messages.js文件:

export Type1 from './messages/type1';
export Type2 from './messages/type2';
...

但是,当我 运行 Babel 在任何执行 import * as Messages from 'package_name/messages' 的文件上时,我没有得到任何结果。 (它只是简单地没有做任何事情)。

当我将文件更改为具有以下内容时,一切正常:

import Type1 from './messages/type1';
import Type2 from './messages/type2';
export {Type1, Type2};
...

为什么其他方法不起作用?

仔细阅读 official spec 可以看出只有两种方法可以使用 export ... from ...:

ExportDeclaration :
    export * FromClause ;
    export ExportClause FromClause ;
    ... // More export declarations

ExportClause :
    { }
    { ExportsList }
    { ExportsList , }

export 的所有其他用途均不接受 FromClause。事实证明,from 的唯一合法用途要么与 * 相关联,要么与大括号括起来的导出列表相关联。没有明确引用就无法使用 default

既然如此,以下文件有效:

export {default as Type1} from './messages/type1';
export {default as Type2} from './messages/type2';
...

我只想补充一点,我遇到了一个非常相似的问题。 Variables/modules 我试图直接从另一个文件导出,结果返回 undefined。但是,如果我通过先导入然后再导出将其分成两步,那就没问题了。问题的原因最终是我在做某种类型的循环导入。