Blog>
Snippets

Dynamic Import of a Redux Middleware with ESM

Explain how to dynamically import a Redux middleware using the ESM import function, which is useful for code splitting and reducing the initial load time of an application.
// store.js
import { createStore, applyMiddleware, compose } from 'redux';
import rootReducer from './reducers';

// Define the initial set of middlewares as an empty array
const middlewares = [];

// Function to dynamically import a middleware
const addMiddleware = async (middlewarePath) => {
  const module = await import(middlewarePath);
  const middleware = module.default;
  middlewares.push(middleware);
  // Reconfigure and replace the current store's middleware
  store.replaceReducer(applyMiddleware(...middlewares)(rootReducer));
};

// Create Redux store with initial middlewares
const store = createStore(rootReducer, {}, compose(applyMiddleware(...middlewares)));

// Export the store and the dynamical middleware addition function
export { store, addMiddleware };
This code snippet demonstrates how to set up a Redux store and dynamically import additional middlewares into the store using the `import()` function provided by ECMAScript modules (ESM). We start with an empty array of middlewares and use the `addMiddleware` function to dynamically import a middleware by its path, and then push it into the middlewares array. Then, we use `store.replaceReducer` to apply the updated set of middlewares to the store. This allows us to dynamically load middleware during runtime, which can aid in splitting code and reducing initial application load time.
// someComponent.js
import { addMiddleware } from './store';

// Call addMiddleware when you want to dynamically import a middleware
addMiddleware('/path/to/your/dynamicMiddleware.js')
  .then(() => {
    console.log('Middleware has been dynamically added to the store.');
  })
  .catch((error) => {
    console.error('Failed to add the middleware dynamically:', error);
  });
This code snippet shows how to use the `addMiddleware` function within a component or any other part of the application. To dynamically add a middleware to the Redux store, you simply call the `addMiddleware` function with the path to the middleware module. After the middleware has been successfully imported and added to the store, a confirmation message is logged to the console. If the import fails for some reason, the error is caught and logged.