Blog>
Snippets

Building and Exporting a Redux Store with Mixed Module Syntax

Demonstrate the creation of a Redux store exporting with ESM while using reducers and middleware written in CJS, highlighting the mixed module syntax handling.
// cjsReducer.js (CommonJS syntax)
const initialState = { value: 0 };

function counterReducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { value: state.value + 1 };
    case 'DECREMENT':
      return { value: state.value - 1 };
    default:
      return state;
  }
}

module.exports = counterReducer;
This is a CommonJS module exporting a reducer for a counter. The reducer handles two actions, increment and decrement, and returns the updated state accordingly.
// cjsMiddleware.js (CommonJS syntax)
function loggerMiddleware(store) {
  return function(next) {
    return function(action) {
      console.log('dispatching', action);
      let result = next(action);
      console.log('next state', store.getState());
      return result;
    };
  };
}

module.exports = loggerMiddleware;
This is a CommonJS module exporting a simple logger middleware for Redux. It logs actions being dispatched and the state after the dispatch.
// createStore.js (ESM syntax)
import { createStore, applyMiddleware } from 'redux';
// Import CommonJS modules using require
const counterReducer = require('./cjsReducer');
const loggerMiddleware = require('./cjsMiddleware');

// Create the Redux store using the imported reducer and middleware
const store = createStore(
  counterReducer,
  applyMiddleware(loggerMiddleware)
);

export default store;
This is an ES Module file where we're creating and exporting a Redux store. It uses ESM syntax for importing createStore and applyMiddleware from Redux and CommonJS syntax (`require`) for importing the reducer and middleware. Then it creates the store using the imported entities and exports it as the default export.