【问题标题】:ES6 module syntax: is it possible to `export * as Name from ...`?ES6 模块语法:是否可以从 ... `export * as Name from ...`?
【发布时间】:2017-06-19 22:05:04
【问题描述】:

查看问题标题。我找到了great reference 的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 的所有命名导出。


This answer 似乎表明这在 TypeScript 中是不可能的;纯 JavaScript 也一样吗?

(这个例子有点做作;实际上我试图有一个 prop-types.js 模块,它使用命名导出以供 React 包内部使用,但也导出 PropTypes 下的 prop 类型定义以供外部使用. 为了这个问题,我试图简化。)

【问题讨论】:

标签: javascript ecmascript-6


【解决方案1】:

不,在 JS 中也不允许,但是有 a proposal to add it。现在,只需使用两步过程,将其导入局部变量并导出:

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

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

【讨论】:

  • 感谢参考!我希望能成功。
【解决方案2】:

2019 年的今天,it is now possible。

export * as name1 from …;

【讨论】:

    【解决方案3】:

    此规范的 proposal 已合并到 ecma262。如果您正在运行以前的 JS 的环境中寻找此功能,那么可以使用 babel plugin !配置插件后(或者如果您使用的是 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'
    

    【讨论】:

      【解决方案4】:
      // 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';
      

      【讨论】:

        猜你喜欢
        • 2023-02-25
        • 1970-01-01
        • 1970-01-01
        • 2017-12-04
        • 1970-01-01
        • 2017-07-08
        • 2019-12-26
        • 2018-03-11
        • 2019-10-23
        相关资源
        最近更新 更多