Blog>
Snippets

Hybrid ESM/CJS Redux Thunk Middleware

Illustrate how to write a Redux thunk middleware that can be used in both ESM and CJS environments, including the correct use of exports and requires.
const createThunkMiddleware = require('./createThunkMiddleware'); // CJS require
module.exports = createThunkMiddleware(); // CJS default export
module.exports.default = module.exports; // ESM-compatible export
This is the CommonJS entry point. It requires the actual thunk middleware implementation and exports it both as the default CommonJS export and as a property named default to be compatible with ESM import syntax.
export { default } from './cjs.js'; // Re-export CJS as default ESM export
This is the ESM entry point. It re-exports the default export from the CommonJS entry point file as the default ESM export. This allows ESM consumers to import the thunk middleware using the standard ESM import syntax.
// createThunkMiddleware.js
function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => next => action => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }
    return next(action);
  };
}

module.exports = createThunkMiddleware; // Export for CJS
export default createThunkMiddleware; // Export for ESM
This is the createThunkMiddleware.js file containing the actual implementation of the Redux thunk middleware. It exports the middleware for both CJS and ESM environments using the appropriate syntax. The middleware checks if the 'action' is a function, and if so, it calls the function with dispatch, getState, and an extra argument. Otherwise, it passes the action to the next middleware.