ai / nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript
https://zelark.github.io/nano-id-cc/
MIT License
24.61k stars 790 forks source link

Error [ERR_REQUIRE_ESM] when using `nanoid` with CommonJS #491

Closed ItsAJ1005 closed 2 months ago

ItsAJ1005 commented 2 months ago

I encountered an issue while using the nanoid package in a Node.js project with CommonJS modules. The error message suggests that require() is not supported for ES Modules and recommends switching to a dynamic import().

Error [ERR_REQUIRE_ESM]: require() of ES Module D:\Web development\Node js\url-shortner\node_modules\nanoid\index.js from D:\Web development\Node js\url-shortner\controllers\urlController.js not supported.
Instead change the require of index.js in D:\Web development\Node js\url-shortner\controllers\urlController.js to a dynamic import() which is available in all CommonJS modules.

    at Object.<anonymous> (D:\Web development\Node js\url-shortner\controllers\urlController.js:1:20)
{
  code: 'ERR_REQUIRE_ESM'
}

Environment:

Node.js version: v20.16.0 nanoid version: ^5.0.7 OS: [Win 10 x64]

Steps to Reproduce: Install nanoid in a Node.js project. Attempt to import nanoid using require() in a CommonJS module. Run the script and observe the error. Expected Behavior:

The nanoid package should work seamlessly with CommonJS using require() or there should be clear documentation on how to import the package in a CommonJS environment.

Actual Behavior:

The application throws an ERR_REQUIRE_ESM error, indicating that the module cannot be required directly and suggesting the use of import() instead.

Workaround:

Currently, the issue can be resolved by switching from require() to import() as follows:

javascript: const { nanoid } = await import('nanoid'); However, this approach requires using top-level await or wrapping the import statement in an async function, which might not be ideal for all use cases.

ai commented 2 months ago
  1. You need to migrate your app to ESM
  2. Or use nanoid@3 if you still using CJS app
  3. Or wait until Node.js will support require() ESM libs (it will be soon)