Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use nanoid without import

I am stuck with an issue, I have to generate a 6 digit alphanumeric CODE which should be unique and for that i am using nanoid, Now when i code this:

 const {nanoid} = require("nanoid");
 const ID = nanoid();

I got error:

    const {nanoid} = require("nanoid");
                 ^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\HP\Desktop\test\node_modules\nanoid\index.js from C:\Users\HP\Desktop\test\server.js not supported.
Instead change the require of index.js in C:\Users\HP\Desktop\test\server.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (C:\Users\HP\Desktop\test\server.js:1:18) {
  code: ←[32m'ERR_REQUIRE_ESM'←[39m
}

if I code this:

import { nanoid } from 'nanoid'
const id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"

i got error:

    (node:4636) 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)
C:\Users\HP\Desktop\test\server.js:4
import { nanoid } from 'nanoid'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Now I have tried changing package.json file

"type":"module"

but my project use babel and it will automatically convert import to require and as result first error come again.

could you please tell me how to do nanoid with require' Thank you

like image 287
mohammad shahab Avatar asked Sep 06 '25 03:09

mohammad shahab


1 Answers

This is a feature, not a bug. See the changelog for details of the breaking change in version 4.0 https://github.com/ai/nanoid/issues/365

like image 94
Minhaj T Avatar answered Sep 07 '25 21:09

Minhaj T