React Native - Dynamically List/Require Files In Directory

只愿长相守 提交于 2019-12-24 09:39:42

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/39901584/react-native-dynamically-list-require-files-in-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!