ES6 exporting/importing in index file

ES6 exporting/importing in index file

I am currently using ES6 in an React app via webpack/babel.
I am using index files to gather all components of a module and export them. Unfortunately, that looks like this:
import Comp1_ from ‘./Comp1.jsx’;
import Comp2_ from ‘./Comp2.jsx’;
import Comp3_ from ‘./Comp3.jsx’;

export const Comp1 = Comp1_;
export const Comp2 = Comp2_;
export const Comp3 = Comp3_;

So I can nicely import it from other places like this:
import { Comp1, Comp2, Comp3 } from ‘./components’;

Obviously that isn’t a very nice solution, so I was wondering, if there was any other way. I don’t seem to able to export the imported component directly.


Solution 1:

You can easily re-export the default import:

export {default as Comp1} from './Comp1.jsx';
export {default as Comp2} from './Comp2.jsx';
export {default as Comp3} from './Comp3.jsx';

There also is a proposal for ES7 ES8 that will let you write export Comp1 from '…';.

Solution 2:

Also, bear in mind that if you need to export multiple functions at once, like actions you can use

export * from './XThingActions';

Solution 3:

Too late but I want to share the way that I resolve it.

Related:  Changing an element's ID with jQuery

Having model file which has two named export:

export { Schema, Model };

and having controller file which has the default export:

export default Controller;

I exposed in the index file in this way:

import { Schema, Model } from './model';
import Controller from './controller';

export { Schema, Model, Controller };

and assuming that I want import all of them:

import { Schema, Model, Controller } from '../../path/';

Solution 4:

I had an issue with export *, it returned undefinedwhen i would import the default function/class …

So, i finally fixed it with export {default} from './MyClass' and it worked as well