如何使用无需导入的nanoid



我遇到了一个问题,我必须生成一个6位数的字母数字代码,这应该是唯一的,为此我使用nanoid,现在,当我编写如下代码:

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

I got error:

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

如果我这样写:

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:UsersHPDesktoptestserver.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

现在我已经尝试更改包。json文件

"type":"module"

但是我的项目使用Babel,它会自动将import转换为require,结果第一个错误再次出现。

你能告诉我如何用require做nanoid吗?谢谢你

这是一个特性,而不是一个bug。有关4.0版本中突破性更改的详细信息,请参阅更改日志https://github.com/ai/nanoid/issues/365

最新更新