Codecept 中的 Nanoid4 错误 [ERR_REQUIRE_ESM]:ES 模块的 require()

问题描述 投票:0回答:4

我更新到 nanoid4 并开始收到以下错误:

[ERR_REQUIRE_ESM]:ES模块的require() [...]/node_modules/nanoid/index.js 不支持。相反,改变 需要 [...]/signup_test.ts 中的 index.js 来动态 import() 所有 CommonJS 模块都可用

这是它抱怨的导入:

import { customAlphabet } from 'nanoid'

这是我正在使用的 tsconfig 文件:

{
    "ts-node": {
      "files": true
    },
    "compilerOptions": {
      "jsx": "react-jsx",
      "types": [
        "node",
        "codeceptjs"
      ],
      "experimentalDecorators": true,
      "lib": [
        "dom",
        "dom.iterable",
        "esnext"
      ],
      "allowJs": true,
      "skipLibCheck": true,
      "strict": false,
      "forceConsistentCasingInFileNames": true,
      "noEmit": true,
      "esModuleInterop": true,
      "module": "ES6",
      "moduleResolution": "node",
      "resolveJsonModule": true,
      "incremental": true,
      "target": "ESNext",
    },
    "include": [
      "next-env.d.ts",
      "**/*.ts",
      "**/*.tsx"
    ],
    "exclude": [
      "node_modules"
    ]
  }

不确定为什么坏了

typescript es6-modules nanoid
4个回答
26
投票

如果您使用其他版本的

nanoid
,它就可以工作。例如:

npm uninstall nanoid
npm install [email protected]

如果没有,请尝试根据

对此
更改您的一些tsconfig.json


17
投票

出现错误“[ERR_REQUIRE_ESM]:不支持 require()”是因为您正在导入的包已转换为仅 ESM 包,这意味着无法再使用 require() 导入该包。 使用 npm i [电子邮件受保护]


2
投票

我将导入更改为: 从“nanoid”导入*作为nanoid; 它起作用了,所以你可以尝试重写你的导入语句

nanoid 文档没有指定这一点,但我只是想了一下并尝试了一下,它起作用了

我希望这对其他人有帮助


0
投票

这可能是微不足道的,但就我而言,问题的根本原因是使用了错误的节点版本。通常我使用

v20.10
,但是
nanoid
软件包是通过
v18.17.1
安装的(npm:
9.6.7
)。

所以切换回

v.20.10
解决了我的问题。

© www.soinside.com 2019 - 2024. All rights reserved.