Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export default modules in index.js barrels

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.

like image 217
Jon Miles Avatar asked Dec 22 '16 19:12

Jon Miles


People also ask

How do I export multiple functions by default?

To export multiple functions in JavaScript, use the export statement and export the functions as an object. Alternatively, you can use the export statement in front of the function definitions. This exports the function in question automatically and you do not need to use the export statement separately.

Is export default JavaScript?

The export statement is used when creating JavaScript modules to export objects, functions, variables from the module so they can be used by other programs with the help of the import statements. There are two types of exports. One is Named Exports and other is Default Exports.

What is barrel export?

A barrel is a way to rollup exports from several modules into a single convenient module. The barrel itself is a module file that re-exports selected exports of other modules.

Can you export with module exports?

Declaring a module. exports object in a file specifies the values to be exported from that file. When exported, another module can import this values with the require global method.


1 Answers

Use the following line:

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

Hope it suits your needs, cheers

like image 86
Iban Dominguez Noda Avatar answered Oct 06 '22 07:10

Iban Dominguez Noda