ES6模块语法:是否可以使用`export * as Name from ...`的方式导出?

33

看问题标题。我找到了一个关于可用的export形式的优秀参考资料,但是我没有找到我需要的。

是否可能像下面这样做?

// file: constants.js
export const SomeConstant1 = 'yay';
export const SomeConstant2 = 'yayayaya';

// file: index.js
export * as Constants from './constants.js';

也就是说,这将在 index.js 中提供一个名为 Constants 的命名导出,其中包含来自 constants.js 的所有命名导出。


这个答案似乎表明在TypeScript中不可能。对于纯JavaScript是否也是如此?

(这个例子有点牵强;实际上我正在尝试使用命名导出创建一个 prop-types.js 模块,在 React 包内部用于内部使用,但同时将 prop 类型定义导出到 PropTypes 以供外部使用。我为了问题的简化而尝试简化了一下。)


4个回答

40

不,JS也不允许这样做,但是有一个提案可以添加它。目前,只需使用导入到本地变量并导出即可进行两步操作:

// file: constants.js
export const SomeConstant1 = 'yay';
export const SomeConstant2 = 'yayayaya';

// file: index.js
import * as Constants from './constants.js';
export {Constants};

谢谢您的参考!我希望它能被采纳。 - vergenzt

30

4

这个规范的提案已经合并到ecma262中。如果您正在运行早期版本的JS环境并且需要此功能,则可以使用babel插件!在配置插件后(或者如果您使用的是ecma262或更高版本),您就可以运行问题中的JS代码:

// file: constants.js
export const SomeConstant1 = 'yay';
export const SomeConstant2 = 'yayayaya';

// file: index.js
export * as Constants from './constants.js';

// file: component.js
import { Constants } from './index.js';

const newVar = Constants.SomeConstant1; // 'yay'

0
// file: index.js
// note, this doesn't have to be at the top, you can put it wherever you prefer
import * as AllExportsFromThisModule from "./index.js"; // point this at the SAME file
export default AllExportsFromThisModule;

export const SOME_CONSTANT = 'yay';
export const SOME_OTHER_CONSTANT = 'yayayaya';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接