2

I am using Redux and would like to dynamically include all files in a directory.

/redux/index.js

// Actions

import * as authActions from './auth/authActions';
import * as deviceActions from './device/deviceActions';
import * as globalActions from './global/globalActions';
import * as menuActions from './menu/menuActions';
... etc

export const actions = [
  authActions,
  deviceActions,
  globalActions,
  menuActions,
...
];

// Reducers

import auth from './auth/authReducer';
import device from './device/deviceReducer';
import global from './global/globalReducer';
import menu from './menu/menuReducer';
...

import { combineReducers } from 'redux';

export const rootReducer = combineReducers({
  auth,
  device,
  global,
  menu,
...
});

In the above (simplified) example, all the files are of the structure:

/redux/
  /auth/
    authActions.js
    authReducer.js
  /device/
    deviceActions.js
    deviceReducer.js
  /global/
    globalActions.js
    globalReducer.js
  /menu/
    menuActions.js
    menuReducer.js
  ...

In this index.js file, it would be much easier to maintain if I could dynamically read all the directories within the redux directory, and dynamically require the actions and reducers to export.

In a regular node environment, I would do something like (not tested, but illustrates the example):

import fs from 'fs'
import path from 'path'
import { combineReducers } from 'redux'

let actions = []
let reducers {}

fs
  .readdirSync(__dirname).filter((file) => {
    // Only directories
    return fs.statSync(path.join(__dirname, file)).isDirectory();
  })
  .forEach((module) => {
    const moduleActions = require(path.join(__dirname, module, `${module}Actions.js`);
    const moduleReducer = require(path.join(__dirname, module, `${module}Reducer.js`);

    actions.push(moduleActions)
    reducers[module] = moduleReducer.default
  });

export actions
export const rootReducer = combineReducers(reducers)

The issue is that the fs module isn't a thing in react-native to be able to dynamically iterate through the directories in the codebase. There is react-native-fs, but that is for actually accessing the filesystem on the device (after the app is compiled) [I think?]. The above is much cleaner than individually requiring all of the actions and reducers, and specifying them in the actions array and reducer object.

Any ideas?

Eric Kerr
  • 21
  • 1
  • 2

1 Answers1

2

Dynamic loading of modules is not supported in react-native. All the javascript files are bundled into one js file.

agenthunt
  • 8,450
  • 3
  • 30
  • 26