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, | |
}), | |
{}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@vikaskulkarni this was a looong time ago but I believe that
!~reducer.indexOf('.js')
is filtering out values that aren'tjs
files, not sure ifrequire.context
has other values. In the regex, it ignores theindex.js
file (which would be this one)