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'
}
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.
I encountered an issue while using the
nanoid
package in a Node.js project with CommonJS modules. The error message suggests thatrequire()
is not supported for ES Modules and recommends switching to a dynamicimport()
.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.