Blog>
Snippets

Default Export Interoperability between CJS and ESM for Redux Enhancers

Show how to export Redux enhancers as default exports in ESM, and to require them properly in CommonJS modules, emphasizing the differences in export/import statements.
// In an ESM file, enhancer.js
export default function myEnhancer(createStore) {
  return function newCreateStore(reducer, preloadedState, enhancer) {
    // enhancer code here
    return createStore(reducer, preloadedState, enhancer);
  };
}
This is an ES module (ESM) where a Redux enhancer function is exported as the default export. It wraps the createStore function to enhance it with additional functionality.
// In a CommonJS file
const myEnhancer = require('./enhancer.js').default;

// Use it with Redux createStore
const { createStore } = require('redux');
const store = createStore(rootReducer, preloadedState, myEnhancer);
This CommonJS module requires the ESM-exported `myEnhancer` function. Since ESM default exports become properties named `default` on the exported object in CommonJS, we access it via `require('./enhancer.js').default`. Then it's used to enhance the Redux store during its creation.