Blog>
Snippets

Converting a Redux Middleware from CJS to ESM

Demonstrate how to refactor a Redux middleware written with CommonJS (CJS) module syntax into ECMAScript Module (ESM) syntax to ensure compatibility with Redux v5.0.0 using export/import statements.
// Redux Middleware in CommonJS (before conversion)
const exampleMiddleware = store => next => action => {
  // Middleware logic here...
  return next(action);
};

module.exports = exampleMiddleware;
This is the original Redux middleware written using CommonJS module syntax. It exports the middleware function using 'module.exports'.
// Export the same middleware as an ECMAScript Module
export default function exampleMiddleware(store) {
  return function(next) {
    return function(action) {
      // Middleware logic here...
      return next(action);
    };
  };
}
Refactored Redux middleware using ESM syntax, replacing 'module.exports' with 'export default', which is the syntax for exporting a single value or function in ESM.
// Importing the refactored Redux middleware in another module using ESM
import exampleMiddleware from './exampleMiddleware.mjs';

// Use the imported middleware in Redux store setup
const store = createStore(
  rootReducer,
  applyMiddleware(exampleMiddleware)
);
Example of how to import the refactored middleware using ESM 'import' syntax and apply it to the Redux store using 'applyMiddleware'.