redux-toolkit: Cannot import redux-toolkit from a Node.js ESM module

I have a bit of an unusual setup where I use redux-toolkit also in the backend of a Node.js application. I am currently in the process of migrating my backend to ESM modules, since some dependencies (in particular node-fetch) are starting to ship only ESM modules.

Error description

When I try to import redux-toolkit in an mjs module using import { createSlice } from '@reduxjs/toolkit';, I am receiving the following error:

SyntaxError: Named export 'createSlice' not found. The requested module '@reduxjs/toolkit' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from '@reduxjs/toolkit';
const { createSlice } = pkg;

The workaround suggested in the error message does work for Node.js mjs files. The problem is that the code where I use redux-toolkit is shared by the backend (running on Node.js) and the frontend (compiled using webpack). With the workaround in place, webpack can now not compile the file anymore and gives the following error:

export 'default' (imported as 'toolkit') was not found in '@reduxjs/toolkit' (possible exports: MiddlewareArray, __DO_NOT_USE__ActionTypes, applyMiddleware, bindActionCreators, combineReducers, compose, configureStore, createAction, createAsyncThunk, createDraftSafeSelector, createEntityAdapter, createImmutableStateInvariantMiddleware, createNextState, createReducer, createSelector, createSerializableStateInvariantMiddleware, createSlice, createStore, current, findNonSerializableValue, freeze, getDefaultMiddleware, getType, isAllOf, isAnyOf, isAsyncThunkAction, isDraft, isFulfilled, isImmutableDefault, isPending, isPlain, isPlainObject, isRejected, isRejectedWithValue, miniSerializeError, nanoid, original, unwrapResult)

Reason for the error

redux-toolkit is bundled in several different formats, among them cjs and esm. The bundles are referenced in package.json in the following way (index.js being a wrapper that includes the cjs bundle):

  "main": "dist/index.js",
  "module": "dist/redux-toolkit.esm.js",

While the module property is probably supported by webpack and other bundlers, it does not seem to be supported by Node.js. Instead, Node.js uses the exports property to support different main files for different environments (see here. Since that is not defined in this case, Node.js requires the file from the main property, which is a CommonJS bundle.

Even forcing Node.js to use the ESM bundle by doing import { createSlice } from '@reduxjs/toolkit/dist/redux-toolkit.esm.js'; does not solve the problem. The problem is that Node.js interprets files as CommonJS unless they have a .jsm file extension or "type": "module" is defined in package.json (which then applies to all files in the package) (see here).

Node.js does support importing CommonJS packages in most cases, but in the case of redux-toolkit for some reason it doesn’t work. I am not sure why, but none of my other dependencies had this problem.

Possible solution

Setting "type": "module" is probably not an option, since that will break the CommonJS files.

The only solution that I can think of is to ship the ESM bundle as an .mjs file, either by renaming the current one or by creating a copy. The file can then be referenced in package.json like this:

  "exports": {
    "import": "./dist/redux-toolkit.esm.mjs",
    "require": "./dist/index.js"
  },

This solution does not solve the problem completely, as redux-toolkit uses immer, which has a similar problem. I have reported that as immerjs/immer#901.

Workaround

Use the import like this:

import * as toolkitRaw from '@reduxjs/toolkit';
const { createSlice } = toolkitRaw.default ?? toolkitRaw;

or in Typescript:

import * as toolkitRaw from '@reduxjs/toolkit';
const { createSlice } = ((toolkitRaw as any).default ?? toolkitRaw) as typeof toolkitRaw;

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 25
  • Comments: 33 (2 by maintainers)

Commits related to this issue

Most upvoted comments

Hiya, folks.

For the record, I am finally trying to get started working on proper ESM support for RTK.

Aaaaand I hate everything about this 😃

I found a workaround that works in both backend and frontend:

import * as toolkitRaw from '@reduxjs/toolkit';
const { createSlice } = toolkitRaw.default ?? toolkitRaw;

or in Typescript:

import * as toolkitRaw from '@reduxjs/toolkit';
const { createSlice } = ((toolkitRaw as any).default ?? toolkitRaw) as typeof toolkitRaw;

FYI folks, I’ve published https://github.com/reduxjs/redux-toolkit/releases/tag/v2.0.0-alpha.4 , which does further improvements to the ESM/CJS package formatting.

I’ve also built up a whole suite of example apps using different build tools (CRA4/5, Next, Vite) and other test projects (Node in ESM and CJS mode, and the arethetypeswrong tool) to verify that the package works as expected in a variety of different environments.

I feel fairly good about the ESM/CJS packaging at this point. Please try out that alpha and give us feedback!

This should now be available in https://github.com/reduxjs/redux-toolkit/releases/tag/v2.0.0-alpha.1 .

Please try that out and let us know if it works!

@SebastianGaud : like I said, I’m working on this right now 😃

@toychicken Yes, because ESM syntax has been pretty standard for writing client-side code for several years now. The Node situation is unfortunate, but not a reason to skip showing ESM imports in examples.

This gets even more confusing with RTK Query. I have a similar situation where I use RTK on both backend and frontend. When using ESM, TypeScript can’t locate declaration files for RTK Query so in the end I ended up doing:

import * as rtkQuery from '@reduxjs/toolkit/dist/query/index.js';
const { buildCreateApi, coreModule, fetchBaseQuery } = ((rtkQuery as any).default ?? rtkQuery) as typeof rtkQuery;
import * as rtkQueryReact from '@reduxjs/toolkit/dist/query/react/index.js';
const { reactHooksModule } = ((rtkQueryReact as any).default ?? rtkQueryReact) as typeof rtkQueryReact;
const createApi = buildCreateApi(
    coreModule(),
    reactHooksModule(),
);

I had to build createApi myself because if I didn’t all RTK Query types would fail to infer. Also I still get webpack warnings so I had to ignore those explicitly in my webpack config as well. Hopefully RTK 2.0 comes and saves me from this madness 😄

@azzazkhan did you see Marks last message and try the 2.0 betas?

Our team uses gen-esm-wrapper to create another .mjs file (koa uses this approach too) and then define a exports field in the package.json file. This patch makes us safely use @reduxjs/redux-toolkit in our ESM jest tests:

diff --git a/dist/redux-toolkit.esm.mjs b/dist/redux-toolkit.esm.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..a0660c23c131aee148178a8b9a5e28252b6d00b7
--- /dev/null
+++ b/dist/redux-toolkit.esm.mjs
@@ -0,0 +1,47 @@
+import mod from "./index.js";
+
+export default mod;
+export const MiddlewareArray = mod.MiddlewareArray;
+export const TaskAbortError = mod.TaskAbortError;
+export const __DO_NOT_USE__ActionTypes = mod.__DO_NOT_USE__ActionTypes;
+export const addListener = mod.addListener;
+export const applyMiddleware = mod.applyMiddleware;
+export const bindActionCreators = mod.bindActionCreators;
+export const clearAllListeners = mod.clearAllListeners;
+export const combineReducers = mod.combineReducers;
+export const compose = mod.compose;
+export const configureStore = mod.configureStore;
+export const createAction = mod.createAction;
+export const createAsyncThunk = mod.createAsyncThunk;
+export const createDraftSafeSelector = mod.createDraftSafeSelector;
+export const createEntityAdapter = mod.createEntityAdapter;
+export const createImmutableStateInvariantMiddleware = mod.createImmutableStateInvariantMiddleware;
+export const createListenerMiddleware = mod.createListenerMiddleware;
+export const createNextState = mod.createNextState;
+export const createReducer = mod.createReducer;
+export const createSelector = mod.createSelector;
+export const createSerializableStateInvariantMiddleware = mod.createSerializableStateInvariantMiddleware;
+export const createSlice = mod.createSlice;
+export const createStore = mod.createStore;
+export const current = mod.current;
+export const findNonSerializableValue = mod.findNonSerializableValue;
+export const freeze = mod.freeze;
+export const getDefaultMiddleware = mod.getDefaultMiddleware;
+export const getType = mod.getType;
+export const isAllOf = mod.isAllOf;
+export const isAnyOf = mod.isAnyOf;
+export const isAsyncThunkAction = mod.isAsyncThunkAction;
+export const isDraft = mod.isDraft;
+export const isFulfilled = mod.isFulfilled;
+export const isImmutableDefault = mod.isImmutableDefault;
+export const isPending = mod.isPending;
+export const isPlain = mod.isPlain;
+export const isPlainObject = mod.isPlainObject;
+export const isRejected = mod.isRejected;
+export const isRejectedWithValue = mod.isRejectedWithValue;
+export const legacy_createStore = mod.legacy_createStore;
+export const miniSerializeError = mod.miniSerializeError;
+export const nanoid = mod.nanoid;
+export const original = mod.original;
+export const removeListener = mod.removeListener;
+export const unwrapResult = mod.unwrapResult;
diff --git a/package.json b/package.json
index 25de569f85e80553a03d3fa8abc80707ff7f8501..a836b4a1ef4cac9dafaacf369d94fecd1d4fa202 100644
--- a/package.json
+++ b/package.json
@@ -23,9 +23,17 @@
     "access": "public"
   },
   "main": "dist/index.js",
   "module": "dist/redux-toolkit.esm.js",
   "unpkg": "dist/redux-toolkit.umd.min.js",
   "types": "dist/index.d.ts",
+  "exports": {
+    ".": {
+      "types": "./dist/index.d.ts",
+      "module": "./dist/redux-toolkit.esm.js",
+      "import": "./dist/redux-toolkit.esm.mjs",
+      "require": "./dist/index.js"
+    }
+  },
   "devDependencies": {
     "@microsoft/api-extractor": "^7.13.2",
     "@size-limit/preset-small-lib": "^4.11.0",

If that can be helpful, I’ve managed to get Redux Toolkit imported properly when running in Mocha through a little patching with patch-package, to:

  • update the package.json file to declare exports as described earlier in the thread
  • fix the use of the thunkMiddleware which gets accessed using thunkMiddleware.default when running inside Node.

Note that the project it runs in has "type": "module" in its package.json (as well as the "postinstall": "patch-package" script required by patch-package, of course)

In case it helps anyone, this is the patches/@reduxjs+toolkit+1.8.4.patch patch file that got generated by patch-package:

diff --git a/node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js b/node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js
index 95beed1..b0d0530 100644
--- a/node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js
+++ b/node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js
@@ -420,10 +420,10 @@ function getDefaultMiddleware(options) {
     var middlewareArray = new MiddlewareArray();
     if (thunk) {
         if (isBoolean(thunk)) {
-            middlewareArray.push(thunkMiddleware);
+            middlewareArray.push((thunkMiddleware.default || thunkMiddleware));
         }
         else {
-            middlewareArray.push(thunkMiddleware.withExtraArgument(thunk.extraArgument));
+            middlewareArray.push((thunkMiddleware.default || thunkMiddleware).withExtraArgument(thunk.extraArgument));
         }
     }
     if (process.env.NODE_ENV !== "production") {
diff --git a/node_modules/@reduxjs/toolkit/package.json b/node_modules/@reduxjs/toolkit/package.json
index 460a8c0..3680368 100644
--- a/node_modules/@reduxjs/toolkit/package.json
+++ b/node_modules/@reduxjs/toolkit/package.json
@@ -118,5 +118,10 @@
   "bugs": {
     "url": "https://github.com/reduxjs/redux-toolkit/issues"
   },
-  "homepage": "https://redux-toolkit.js.org"
+  "homepage": "https://redux-toolkit.js.org",
+  "type": "module",
+  "exports": {
+    "import": "./dist/redux-toolkit.esm.js",
+    "require": "./dist/index.js"
+  }
 }

If you’re looking to patch the library further (for ex. to remove the enableES5() call), seems patch-package can only handle one patch per library, so you’ll need to make sure to generate your own patch after editing further. To make sure the changes in package.json get in the patch, there’s a little twist and you’ll need to add the --exclude flag for generating the patch : npx patch-package --exclude.

Just FYI - all the examples on the Redux Toolkit site uses ESM imports - might be why some are confused here! e.g. https://redux-toolkit.js.org/api/createReducer