Blog>
Snippets

Correct Usage of Module Formats

Contrast a faulty piece of code mixing ESM with CJS in Redux and correct it according to best practices for module usage.
// Correct Usage: Importing an ESM default export into a Redux store
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers'; // Assume rootReducer is an ESM default export

const store = createStore(
    rootReducer,
    applyMiddleware(thunk)
);

export default store;
This piece of code demonstrates how to correctly import ESM default exports, such as applyMiddleware from Redux, and a rootReducer default export from an ESM module. Then it creates and exports a Redux store using createStore with the imported middleware and reducer.
// Faulty Code Mixing ESM with CJS in Redux

// Incorrect import of CommonJS module as if it were ESM
import rootReducer from 'reducers.cjs';
import { createStore } from 'redux';

const store = createStore(rootReducer);

// Corrected Code Importing CJS into ESM

// Use dynamic import() or interopRequireDefault for importing CJS modules
import { createStore } from 'redux';
const interopRequireDefault = (module) => (module && module.__esModule ? module : { default: module });

async function configureStore() {
  const rootReducer = interopRequireDefault(await import('reducers.cjs')).default;
  const store = createStore(rootReducer);
  return store;
}
This code first shows an incorrect attempt to import a CommonJS module as if it were using ESM syntax, which can lead to errors or unexpected behavior. It is corrected by using an interopRequireDefault function that works around CommonJS and ESM interoperation issues, combined with dynamic import() to load a CommonJS module in an ESM environment.