configureStore.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * Create the store with dynamic reducers
  3. */
  4. import { createStore, applyMiddleware, compose, Store, ReducersMapObject } from 'redux'
  5. import { routerMiddleware } from 'connected-react-router'
  6. import { History } from 'history'
  7. import createSagaMiddleware, { Task, SagaIterator } from 'redux-saga'
  8. import createReducer from './reducers'
  9. import { apiInterceptorMiddleware } from 'utils/statistic/apiInterceptorMiddleware'
  10. export interface IStore<T> extends Store<T> {
  11. runSaga?: (saga: (...args: any[]) => SagaIterator, ...args: any[]) => Task
  12. // asyncReducers?: ReducersMapObject,
  13. injectedReducers?: ReducersMapObject,
  14. injectedSagas?: ReducersMapObject
  15. }
  16. export interface IWindow extends Window {
  17. // __REDUX_DEVTOOLS_EXTENSION_COMPOSE__: typeof compose
  18. __REDUX_DEVTOOLS_EXTENSION_COMPOSE__: any
  19. }
  20. declare const window: IWindow
  21. export default function configureStore<T> (initialState = {}, history: History<any>): IStore<T> {
  22. let composeEnhancers = compose
  23. const reduxSagaMonitorOptions = {}
  24. // If Redux Dev Tools and Saga Dev Tools Extensions are installed, enable them
  25. /* istanbul ignore next */
  26. if (process.env.NODE_ENV !== 'production' && typeof window === 'object') {
  27. /* eslint-disable no-underscore-dangle */
  28. if (window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) {
  29. composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
  30. }
  31. // NOTE: Uncomment the code below to restore support for Redux Saga
  32. // Dev Tools once it supports redux-saga version 1.x.x
  33. // if (window.__SAGA_MONITOR_EXTENSION__)
  34. // reduxSagaMonitorOptions = {
  35. // sagaMonitor: window.__SAGA_MONITOR_EXTENSION__,
  36. // }
  37. /* eslint-enable */
  38. }
  39. const sagaMiddleware = createSagaMiddleware(reduxSagaMonitorOptions)
  40. // Create the store with two middlewares
  41. // 1. statistics middleware
  42. // 2. sagaMiddleware: Makes redux-sagas work
  43. // 3. routerMiddleware: Syncs the location/URL path to the state
  44. const middlewares = [apiInterceptorMiddleware, sagaMiddleware, routerMiddleware(history)]
  45. const enhancers = [applyMiddleware(...middlewares)]
  46. const store: IStore<T> = createStore(
  47. createReducer(),
  48. initialState,
  49. composeEnhancers(...enhancers)
  50. )
  51. // Extensions
  52. store.runSaga = sagaMiddleware.run
  53. store.injectedReducers = {} // Reducer registry
  54. store.injectedSagas = {} // Saga registry
  55. // Make reducers hot reloadable, see http://mxs.is/googmo
  56. /* istanbul ignore next */
  57. if (module.hot) {
  58. module.hot.accept('./reducers', () => {
  59. store.replaceReducer(createReducer(store.injectedReducers))
  60. })
  61. }
  62. return store
  63. }