Blog>
Snippets

Integrating a CJS Third-Party Middleware into Redux with ESM

Show how to integrate a CommonJS third-party Redux middleware into an ESM-based Redux configuration by utilizing interopRequireDefault for compatibility.
import { createStore, applyMiddleware } from 'redux';
import interopRequireDefault from '@babel/runtime/helpers/interopRequireDefault';

// Assuming 'cjsMiddleware' is your CommonJS middleware
const cjsMiddleware = interopRequireDefault(require('cjs-middleware-package')).default;

// Your root reducer
function rootReducer(state = {}, action) {
  // ...reducers logic...
  return state;
}

// Apply middleware to the Redux store
const store = createStore(
  rootReducer,
  applyMiddleware(cjsMiddleware)
);

export default store;
The code snippet above demonstrates how to integrate a CommonJS middleware into an ESM-based Redux configuration. It first imports the required ESM modules from Redux and the interopRequireDefault helper from Babel. It uses interopRequireDefault to import the middleware as default and then creates a Redux store using createStore and applyMiddleware functions, finally applying the middleware to the store.