Created
June 30, 2016 17:40
-
-
Save goldhand/3d2cb9a468ba8823f9bc1479f03cf137 to your computer and use it in GitHub Desktop.
Redux root reducer that uses webpack's require.context to create a rootReducer that dynamically imports reducers in a directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this file should actually be in reducers/index.js | |
import {combineReducers} from 'redux'; | |
const rootReducer = combineReducers( | |
allReducers(require.context('.', false, /^\.\/(?!index)\w+$/)) | |
); | |
export default rootReducer; | |
function allReducers(requireContext) { | |
return requireContext | |
.keys() | |
.filter(reducer => !~reducer.indexOf('.js')) | |
.reduce( | |
(reducers, reducer) => ({ | |
...reducers, | |
[reducer.substr(2)]: requireContext(reducer).default, | |
}), | |
{}); | |
} |
@vikaskulkarni this was a looong time ago but I believe that !~reducer.indexOf('.js')
is filtering out values that aren't js
files, not sure if require.context
has other values. In the regex, it ignores the index.js
file (which would be this one)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you should put some comments on what you are doing. For example, I am not able to figure out this filter;
.filter(reducer => !~reducer.indexOf('.js'))
And also the regex in identifying the files