Skip to content

Instantly share code, notes, and snippets.

@goldhand
Created June 30, 2016 17:40
Show Gist options
  • Save goldhand/3d2cb9a468ba8823f9bc1479f03cf137 to your computer and use it in GitHub Desktop.
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 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
Copy link

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

@goldhand
Copy link
Author

goldhand commented Aug 3, 2020

@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