332

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;

but this does not work. I have to write:

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

But this is odd. What is the right way to do this?

4
  • why would you export react? Commented May 13, 2016 at 2:33
  • you can export {React} but again, if you need React somewhere, you should just import it there. Commented May 13, 2016 at 2:45
  • 3
    export react is just an example, in fact, I want organize some project so that user can import some object in shorter and high level path. Commented May 13, 2016 at 3:15
  • @YaoZhao Do not include solution to question please (post a separate answer instead). Commented Jun 12 at 10:17

4 Answers 4

181

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
Sign up to request clarification or add additional context in comments.

Comments

57

You could export imported file with such structure

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

Comments

1

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;

Comments

-2

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

1 Comment

That's not quite what the question was about?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.