How to export default modules in index.js barrels

Jonathan Miles picture Jonathan Miles · Dec 22, 2016 · Viewed 7.2k times · Source

I'm trying to export default modules using index.js barrels but can't seem to get it to work. It works fine with named exports but not default exports.

Simplified Project Structure

/hellos
  /components
    Hello.js
    Hellos.js
    index.js
  index.js
App.js

/hellos/component/Hellos.js

...
export default Hellos

/hellos/component/index.js

export * from './Hello';
export * from './Hellos';

/hellos/index.js

export * from './components'
export * from './actions'
export * from './constants'
export * from './reducers'

App.js

import Hellos from './hellos'
console.log(Hellos) // <- undefined

The Hellos module imported just above is always undefined.

I can get it to work using either named exports or a direct import in App.js i.e. import Hellos from './hellos/component/Hellos' but I consider this bad practice and only wish to use import Hellos from '/hellos'.

I suspect the problem is with the index.js barrels but I can't work it out. Please help.

Answer

Iban Dominguez Noda picture Iban Dominguez Noda · Aug 1, 2017

Use the following line:

export { default as MyModule } from 'src/MyModule'

Hope it suits your needs, cheers