How to export imported object in ES6?

后端 未结 5 455
孤城傲影
孤城傲影 2020-12-07 06:55

The use case is simple: I just want to export an object with the name just as it was imported.

for example:

import React from \'react\';
export React         


        
相关标签:
5条回答
  • 2020-12-07 07:22

    You should be able to do export {React} and import it via import {React} from ./module

    See https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export for more information.

    0 讨论(0)
  • 2020-12-07 07:25

    I often do the following in index.js files that compose several files:

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

    This blog entry provides some nice additional examples.

    Important note

    You should be aware this eslint-rule when accessing these exported imports. Basically, in another file, you shouldn't:

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

    You should do this:

    import SomeClassModule, {someFunction} from 'SomeClass/index.js';
    someFunction(); // Ok
    
    0 讨论(0)
  • 2020-12-07 07:27

    You could export imported file with such structure

    import First from './First'
    import Second from './Second'
    /..../
    export { First, Second }
    
    0 讨论(0)
  • 2020-12-07 07:30

    For my use case, I explicitly need some sort of explicit import statement so that babel can transpile my es7 code to es5.

    The following results in an error 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'
    

    My solution was to explicitly import the module by using require():

    require( 'babel-core/register' );
    export default require( './module_name' ).default;
    
    0 讨论(0)
  • 2020-12-07 07:32

    Given ./foo.js:

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

    Then you should be able to do this:

    import Foo from './foo';
    
    let foo = new Foo();
    
    foo.talk(); // => 'hello';
    

    The syntax more or less follows the commonjs module.exports pattern, where you would do this:

    const Foo = class {
    
    };
    
    module.exports = Foo;
    

    More here:

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

    0 讨论(0)
提交回复
热议问题