Consider following file structure of JavaScript files of a redux project (which is not that important but it's a real life scenario):
plugins/
a/reducer.js
b/reducer.js
c/reducer.js
rootReducer.js
This is the current content of rootReducer.js
:
import { combineReducers } from 'redux'
import a from './a/reducer'
import b from './b/reducer'
import c from './c/reducer'
export default combineReducers({ a, b, c });
Note that each of the reducer.js
files default exports a reducer function.
To add a new plugin, I create an appropriate folder, add a new reducer.js
file to it and then I need to manually import the reducer file and register it in rootReducer.js
.
I would like this process to be fully automatic. I want the rootReducer.js
file to go through all the subdirectories, look for a file reducer.js
inside of them and eventually import it and add it to the root reducer using the folder name.
I'm using webpack and babel to compile and bundle my JavaScript files.
I know that there is a file system API in Node.js which would allow me to iterate through the folders and look for the reducer.js
file. But is it going to work correctly once bundled with webpack? Is it safe to dynamically import modules/files?