How to consolidate named exports from multiple fil

2019-03-03 15:57发布

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?

3条回答
乱世女痞
2楼-- · 2019-03-03 16:35

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.

查看更多
Bombasti
3楼-- · 2019-03-03 16:35

In searching for a consistent export / import pattern, this is one possible solution.

using this for all imports:

import alpha from './alpha' (no star)

For the exports:

export default {
  ...module.exports,
  ...alpha
}

This groups everything with a export before it, as well as everything exported from alpha.

查看更多
再贱就再见
4楼-- · 2019-03-03 16:42

I believe the problem is in your actions/index.js

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

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

Since you're exporting as default, you would have to import like this:

import actions from '../actions'

actions.action1(...)

This will not work:

import { action1 } from '../actions'

actions.action1(...) // Error: action1 is undefined

The destructuring syntax can only grab named exports, but you're using a default export.

I'd like to be able to create named exports with object spread, but alas, it is not valid syntax:

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

export {
  ...actions1, // object spread cannot be used in an export like this
  ...actions2
}
查看更多
登录 后发表回答