How to export default modules in index.js barrels
Asked Answered
O

3

21

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.

Orogeny answered 22/12, 2016 at 19:18 Comment(3)
I think you want something like export { default as Hello } from './Hello'; in your component index file.Contributor
Yeah that seems to fix the problem. ThanksOrogeny
To automate index.js creation you can use github.com/gajus/create-indexDuodecillion
A
47

Use the following line:

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

Hope it suits your needs, cheers

Adamandeve answered 31/7, 2017 at 22:35 Comment(1)
If your tsconfig needs to set "isolatedModules": true, (it's mandatory in some react projects), you need to write export { type default as MyModule } from 'src/MyModule' instead. Looks a bit strange, but resolves everything clean.Nigeria
M
1

For completeness sake, it is also possible to import them first, then export them under the imported name:

import Something from "./somewhere/whatever";

export { Something };
Matronage answered 26/6, 2023 at 15:46 Comment(0)
M
0

For those using babel

Use babel-plugin-transform-export-extensions plugin like this in your .babelrc:

  "plugins": [
    "babel-plugin-transform-export-extensions",
    "transform-es2015-modules-commonjs"
  ]

And then install the plugin like this:

npm install --save-dev babel-plugin-transform-export-extensions
npm install --save-dev babel-plugin-transform-es2015-modules-commonjs

Then u can use export in index.js simply like this:

export simple from './simple';
export restClient from './jsonServer';
export * from './types';

For those using earlier babel versions, simply use the commonjs module.

Midsummer answered 7/11, 2017 at 12:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.