【问题标题】:How to export imported object in ES6?如何在 ES6 中导出导入的对象?
【发布时间】:2016-09-09 01:33:36
【问题描述】:

用例很简单:我只想导出一个名称与导入时一样的对象。

例如:

import React from 'react';
export React;

但这不起作用。我必须写:

import React from 'react';
export const React = React;

但这很奇怪。这样做的正确方法是什么?

更新

感谢您的帮助和参考。我已经用很多线索解决了我的问题。我想分享一些我的常见案例和解决方案。

出口进口

import d, {obj} from '...';

export {obj, d};
export {obj as name1, d as name2};

重新导出所有命名的导入

export * from '...';
export * as name1 from '...';

重新导出一些命名的导入

export {a, b as name1} from '...';

将默认导入重新导出为默认导出

export {default} from '...';

将默认导入重新导出为命名导出

export {default as name1} from '...';

【问题讨论】:

  • 为什么要导出react?
  • 你可以export {React} 但同样,如果你在某个地方需要 React,你应该把它导入那里。
  • export react 只是一个例子,实际上我想组织一些项目,以便用户可以在更短和更高级别的路径中导入一些对象。
  • export * as name1 from '...'; 这对我不起作用(使用 webpack 2)。有什么想法吗?
  • 有人有export * as name1 from '...'; 的解决方法吗?

标签: import export ecmascript-6


【解决方案1】:

您应该可以使用export {React} 并通过import {React} from ./module 导入

更多信息请参见https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

【讨论】:

  • 问题不是这个。
【解决方案2】:

给定./foo.js

const Foo = class {
  talk() { return 'hello'; }
};

export default Foo;

那么你应该可以做到这一点:

import Foo from './foo';

let foo = new Foo();

foo.talk(); // => 'hello';

语法或多或少遵循 commonjs module.exports 模式,你可以这样做:

const Foo = class {

};

module.exports = Foo;

更多:

http://exploringjs.com/es6/ch_modules.html

【讨论】:

  • 这不是问题所在?
【解决方案3】:

我经常在组成多个文件的 index.js 文件中执行以下操作:

export {default as SomeClass} from './SomeClass';
export {someFunction} from './utils';
export {default as React} from 'react';

blog entry 提供了一些不错的附加示例。

重要提示

在访问这些导出的导入时,您应该注意这个eslint-rule。基本上,在另一个文件中,您不应该:

import SomeClassModule from 'SomeClass/index.js';
SomeClassModule.someFunction(); // Oops, error

你应该这样做:

import SomeClassModule, {someFunction} from 'SomeClass/index.js';
someFunction(); // Ok

【讨论】:

    【解决方案4】:

    您可以导出具有这种结构的导入文件

    import First from './First'
    import Second from './Second'
    /..../
    export { First, Second }
    

    【讨论】:

      【解决方案5】:

      对于我的用例,我明确需要某种明确的 import 语句,以便 babel 可以将我的 es7 代码转换为 es5。

      以下导致错误You gave us a visitor for the node type "ForAwaitStatement" but it's not a valid type

      require( 'babel-core/register' ); //transpiles es7 to es5
      export {default} from './module_name'
      

      我的解决方案是使用require() 显式导入模块:

      require( 'babel-core/register' );
      export default require( './module_name' ).default;
      

      【讨论】:

        猜你喜欢
        • 2019-06-27
        • 2016-11-16
        • 2023-03-17
        • 2015-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-01
        • 2016-06-10
        相关资源
        最近更新 更多