react-dropzone: [BUG] react-dropzone cannot be imported in a Node.js ESM environment

I am experimenting with React SSR in a project that uses ESM ("type": "module" is set in package.json). The project uses react-dropzone, and although it will not be part of the server-side render, the app still imports it.

Importing react-dropzone in such an environment fails with the following error:

import { useDropzone } from "../node_modules/react-dropzone/dist/index.js";
         ^^^^^^^^^^^
SyntaxError: Named export 'useDropzone' not found. The requested module '../node_modules/react-dropzone/dist/index.js' is a CommonJS module, which may not support all module.exports as named exports.

The combination of two problems leads to this error:

  • react-dropzone’s package.json specifies a main and module field. Node.js only interprets the main field, which leads to the CJS build. To fix this problem, an exports field should be defined whose import property points to the ESM build.
  • The ESM build (under dist/es/index.js) is interpreted by Node.js as a CJS file, since no type is set in package.json and the file has a .js extension. To fix this problem, an ESM build with .mjs file extensions should be provided.

To fix the problem in a backwards-incompatible way (making a major release necessary):

  • Rename the files in dist/es from .js to .mjs
  • Add an exports field to package.json: "exports": { "import": "dist/es/index.mjs", "default": "dist/index.js" }

To fix the problem in a backwards-compatible way:

  • Create an additional (identical) ESM build using .mjs extensions, for example in dist/mjs
  • Add an exports field to package.json: “exports”: { “.”: { “import”: “dist/mjs/index.mjs”, “default”: “dist/index.js” }, “./": "./” }`

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 13
  • Comments: 33

Most upvoted comments

Hi everyone, I’ve created a temporary package react-dropzone-esm which works correctly with modern frameworks. The package provides both esm and cjs bundles. Exports in package.json are properly configured (you can check the difference between react-dropzone and react-dropzone-esm).

The package can be used as a drop-in replacement for react-dropzone – the source code was not modified, I’ve changed only the build system.

Hey I’m using remix with vite. I fix this by adding ssr.noExternal in vite.config.ts. I think it just tells vite to bundle with ssr processing.

export default defineConfig({
    plugins: [
        remix({
            future: {
                v3_fetcherPersist: true,
                v3_relativeSplatPath: true,
                v3_throwAbortReason: true,
                v3_singleFetch: true,
                v3_lazyRouteDiscovery: true,
            },
            routes: async defineRoutes => {
                return flatRoutes(
                    ['routes', ...getPluginRoutes()],
                    defineRoutes
                )
            },
        }),
        tsconfigPaths(),
    ],
    ssr: {
        noExternal: ['lucide-react', 'react-dropzone'],
    },
})

Here’s a patch-package snippet in the meantime in case it helps others.

react-dropzone+14.2.3.patch

diff --git a/node_modules/react-dropzone/dist/es/index.js b/node_modules/react-dropzone/dist/es/index.mjs
similarity index 99%
rename from node_modules/react-dropzone/dist/es/index.js
rename to node_modules/react-dropzone/dist/es/index.mjs
index 39d9345..5deaac3 100755
--- a/node_modules/react-dropzone/dist/es/index.js
+++ b/node_modules/react-dropzone/dist/es/index.mjs
@@ -37,7 +37,7 @@ function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) r
 import React, { forwardRef, Fragment, useCallback, useEffect, useImperativeHandle, useMemo, useReducer, useRef } from "react";
 import PropTypes from "prop-types";
 import { fromEvent } from "file-selector";
-import { acceptPropAsAcceptAttr, allFilesAccepted, composeEventHandlers, fileAccepted, fileMatchSize, canUseFileSystemAccessAPI, isAbort, isEvtWithFiles, isIeOrEdge, isPropagationStopped, isSecurityError, onDocumentDragOver, pickerOptionsFromAccept, TOO_MANY_FILES_REJECTION } from "./utils/index";
+import { acceptPropAsAcceptAttr, allFilesAccepted, composeEventHandlers, fileAccepted, fileMatchSize, canUseFileSystemAccessAPI, isAbort, isEvtWithFiles, isIeOrEdge, isPropagationStopped, isSecurityError, onDocumentDragOver, pickerOptionsFromAccept, TOO_MANY_FILES_REJECTION } from "./utils/index.mjs";
 /**
  * Convenience wrapper component for the `useDropzone` hook
  *
@@ -383,7 +383,7 @@ var initialState = {
  * @function useDropzone
  *
  * @param {object} props
- * @param {import("./utils").AcceptProp} [props.accept] Set accepted file types.
+ * @param {import("./utils/index.mjs").AcceptProp} [props.accept] Set accepted file types.
  * Checkout https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker types option for more information.
  * Keep in mind that mime type determination is not reliable across platforms. CSV files,
  * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under
@@ -969,4 +969,4 @@ function reducer(state, action) {
 
 function noop() {}
 
-export { ErrorCode } from "./utils";
\ No newline at end of file
+export { ErrorCode } from "./utils/index.mjs";
\ No newline at end of file
diff --git a/node_modules/react-dropzone/dist/es/utils/index.js b/node_modules/react-dropzone/dist/es/utils/index.mjs
similarity index 99%
rename from node_modules/react-dropzone/dist/es/utils/index.js
rename to node_modules/react-dropzone/dist/es/utils/index.mjs
index 8e5abd5..f155743 100644
--- a/node_modules/react-dropzone/dist/es/utils/index.js
+++ b/node_modules/react-dropzone/dist/es/utils/index.mjs
@@ -26,7 +26,9 @@ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Sy
 
 function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
 
-import accepts from "attr-accept"; // Error codes
+import _accepts from "attr-accept"; // Error codes
+
+const accepts = typeof _accepts === "function" ? _accepts : _accepts.default;
 
 export var FILE_INVALID_TYPE = "file-invalid-type";
 export var FILE_TOO_LARGE = "file-too-large";
diff --git a/node_modules/react-dropzone/package.json b/node_modules/react-dropzone/package.json
index 9409558..97b8175 100644
--- a/node_modules/react-dropzone/package.json
+++ b/node_modules/react-dropzone/package.json
@@ -2,7 +2,13 @@
   "name": "react-dropzone",
   "description": "Simple HTML5 drag-drop zone with React.js",
   "main": "dist/index.js",
-  "module": "dist/es/index.js",
+  "module": "dist/es/index.mjs",
+  "exports": {
+    ".": {
+      "import": "./dist/es/index.mjs",
+      "require": "./dist/index.js"
+    }
+  },
   "sideEffects": false,
   "scripts": {
     "cz": "git-cz",

I’m still getting this issue in 14.2.6:

(node:50197) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
1:57:20 PM [vite] Error when evaluating SSR module /app/routes/pages/user/complete-profile.tsx: failed to import "react-dropzone"
|- /Users/<user>/Documents/Projects/onde-vamos/node_modules/.pnpm/react-dropzone@14.2.6_react@18.3.1/node_modules/react-dropzone/dist/es/index.js:37
import React, { forwardRef, Fragment, useCallback, useEffect, useImperativeHandle, useMemo, useReducer, useRef } from "react";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:77:18)
    at wrapSafe (node:internal/modules/cjs/loader:1288:20)
    at Module._compile (node:internal/modules/cjs/loader:1340:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at cjsLoader (node:internal/modules/esm/translators:356:17)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:305:7)
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
    at async nodeImport (file:///Users/<user>/Documents/Projects/onde-vamos/node_modules/.pnpm/vite@5.4.7_@types+node@22.5.5_terser@5.31.6/node_modules/vite/dist/node/chunks/dep-DG6Lorbi.js:52998:15)
    at async ssrImport (file:///Users/<user>/Documents/Projects/onde-vamos/node_modules/.pnpm/vite@5.4.7_@types+node@22.5.5_terser@5.31.6/node_modules/vite/dist/node/chunks/dep-DG6Lorbi.js:52856:16)
    at async eval (/Users/<user>/Documents/Projects/onde-vamos/packages/web/app/routes/pages/user/complete-profile.tsx:14:32)
    at async instantiateModule (file:///Users/<user>/Documents/Projects/onde-vamos/node_modules/.pnpm/vite@5.4.7_@types+node@22.5.5_terser@5.31.6/node_modules/vite/dist/node/chunks/dep-DG6Lorbi.js:52914:5)

have the same problem with latest version of react-dropzone , using with latest version of remix + vite. now using react-dropzone-esm and it’s working fine.

Thanks for confirming. I’m glad you found a workaround for now. Hopefully, our ESM compatible version will be out soon if you’d still like to use our lib at that point.

Can confirm this issue using https://github.com/Nic13Gamer/better-upload with Tanstack start using version 14.3.5

fix for Tanstack start is

// app.config.ts
routers: {
        ssr: {
            vite: {
                ssr: {
                    noExternal: ['react-dropzone'],
                },
            },
        },
    },

@bertho-zero we’re slowly working towards an fully ESM package.

@rolandjitsu I still have the issue with the latest version

Lifesaver @gjc14, I’m also using Remix and a google search led me straight here - works great!

I think that there are still some issues with the config in package.json. As pointed out by someone, there are lint errors when using publint.

I will try to look into it next week after I fix my notebook (screen just got damaged). Unless someone already has a PR to fix that by then.

On Sat, Oct 5, 2024, 16:50 Hasan Baki Kucukcakiroglu < @.***> wrote:

I’m still getting this issue in 14.2.9. I started to use react-dropzone-esm and it works well.

— Reply to this email directly, view it on GitHub https://github.com/react-dropzone/react-dropzone/issues/1259#issuecomment-2395065505, or unsubscribe https://github.com/notifications/unsubscribe-auth/AALJIOJ2EGJUUHEPZWD6ONTZZ7VD3AVCNFSM6AAAAAAS7DOVV6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDGOJVGA3DKNJQGU . You are receiving this because you modified the open/close state.Message ID: @.***>

It would be great if you could make a PR that adds the same support.

I’ve spent some time trying to change only the build tool, but had to:

  • rewrite the entire build system to support new formats
  • remove some code/parts of the repository as they were incompatible with the new build
  • move all dependencies into the same repo as some or all of them had the same esm issue (I do not remember all exact details about other packages)

For everything to work correctly, exports in package.json must look something like this:

  "types": "./types/react-dropzone.d.ts",
  "main": "./dist/cjs/index.js",
  "module": "./dist/esm/index.mjs",
  "exports": {
    ".": {
      "import": {
        "types": "./types/react-dropzone.d.mts",
        "default": "./dist/esm/index.mjs"
      },
      "require": {
        "types": "./types/react-dropzone.d.ts",
        "default": "./dist/cjs/index.js"
      }
    }
  },

It is also worth checking publint to verify that everything can be interpreted correctly (currently there are several issues) – https://publint.dev/react-dropzone@14.2.6

You are also welcome to take any part of the source code that I’ve written for react-dropzone-esm package as is or as reference – https://github.com/rtivital/react-dropzone-esm