Blog>
Snippets

Sharing Redux Actions between CJS and ESM

Provide an example of how to create Redux actions that can be shared between modules using both CommonJS and ES Module syntax without compatibility issues in Redux v5.0.0.
// actions.js
// Define a redux action using a function
function increaseCounter(amount) {
    return {
        type: 'INCREASE_COUNTER',
        payload: amount,
    };
}

// Export the function for CommonJS compatibility
module.exports.increaseCounter = increaseCounter;

// Also export using ESM named export for ESM compatibility
// Note: Only works if your environment supports dual-module packages
export { increaseCounter };
This code creates a Redux action named 'increaseCounter' and exports it using both CommonJS and ES Module syntax. The action includes a type and a payload, which is the amount by which the counter should be increased. The module.exports line is for CommonJS compatibility, while the export line is for ES Module compatibility, assuming that the environment supports dual-module packages.
// Using the action in a CommonJS module (CJSModule.js)
const actions = require('./actions');

// Dispatch the action with an amount
store.dispatch(actions.increaseCounter(10));
This CommonJS module requires the actions defined in 'actions.js' and dispatches the 'increaseCounter' action, passing 10 as an argument to increase the counter amount.
// Using the action in an ES Module (ESMModule.js)
import { increaseCounter } from './actions';

// Dispatch the action with an amount
store.dispatch(increaseCounter(10));
This ES Module imports the 'increaseCounter' action from 'actions.js' using named import syntax and dispatches the 'increaseCounter' action, passing 10 as an argument to increase the counter amount.