有没有办法要求将多个模块放入一个文件中,然后再将其作为单个模块导出?

时间:2018-05-03 16:19:04

标签: reactjs module redux export require

目前正在使用Redux,并想知道是否有办法在多个模块中要求单个文件,然后再将其作为单个模块导出?

例如,在我的actions/bookmark.js我将与书签相关的所有操作分组:

module.exports = {
  fetchBookmarkList: () => {
    return {
      type: 'FETCH_LIST'
    }
  },
  fetchBookmark: () => {
    return {
      type: 'FETCH_BOOKMARK'
    }
  }
}

然后在我的actions/index.js文件中,我要求所有操作组(包括书签操作以及其他操作)。然后我想将整个文件导出为单个模块。

示意图我有类似的东西(显然这段代码不起作用):

actions/index.js

module.exports = {
  require('./bookmark');
  require('./tags');
}

我想这样做的原因是我只需要导入包含我所有操作的单个操作文件(即actions/index.js文件):

示例组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions';

class BookmarkList extends Component {
  constructor(props) {
    super(props);
    this.props.fetchBookmarkList();
  }

  render() {
    return (
      <div></div>
    );
  }
}

export default connect(null, actions)(BookmarkList);

2 个答案:

答案 0 :(得分:0)

我在组件中看到es6模块语法,为什么不在你的redux文件中?

export const fetchBookmarkList = () => {
  return {
    type: 'FETCH_LIST'
  }
};

export const fetchBookmark = () => {
  return {
    type: 'FETCH_BOOKMARK'
  }
}

基于this reference我认为可以重新导出这样的所有内容:

export * from './bookmark'
export * from './tags;

但是没试过,我可能错了。

答案 1 :(得分:0)

我会建议您将所有操作传递给mapDispatchToProps,只传递组件所需的操作

但你可以在actions/index.js中使用:

使用点差运算符:

module.exports = {
  ...require('./bookmark');
  ...require('./tags');
} 

在ES6语法中:

actions/index.js

export * from './bookmark'
export * from './tags'