Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consolidate named exports from multiple files and export as one object

I have a lot of action creators that I am trying to organize into a few different files. Each separate file has exported functions like:

export function addData(data) {
  return {
    type: 'ADD_DATA',
    data
  }
}

Before they were separated into distinct files, they were imported like:

import { addData } from './actions/actionCreators'

However with the structure now like

├─┬ actions
│ ├── actionsCreators1.js
│ ├── actionsCreators2.js
│ └── index.js

I would like to consolidate them in the index file and export them as they were initially named. What I have tried is:

actions/index.js

import * as actions1 from './actionCreators1'
import * as actions2 from './actionCreators2'

export default {
  ...actions1,
  ...actions2
}

However the named functions are undefined when imported. I can bring them in individually import { action1, action2 } from './actionCreatos1' and it will work, however it's not ideal to have to write everything in two places.

How can consolidate these imports and export them as one object?

like image 520
1252748 Avatar asked Sep 15 '25 09:09

1252748


1 Answers

Rather than relying on spread, you can use the module system itself to pass the names through, e.g.

// actions/index.js

export * from './actionCreators1'
export * from './actionCreators2'

so as long as the names in the files don't collide, they will just be passed through nicely.

like image 160
loganfsmyth Avatar answered Sep 17 '25 23:09

loganfsmyth