【问题标题】:Nanoid4 in codecept error [ERR_REQUIRE_ESM]: require() of ES ModuleNanoid4 代码错误 [ERR_REQUIRE_ESM]: ES 模块的 require()
【发布时间】:2022-11-23 19:52:07
【问题描述】:

我更新到 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"
    ]
  }

不确定为什么它坏了

【问题讨论】:

  • 您是否查看了生成的 Javascript(不是您的 TypeScript 源代码)以查看实际执行的代码。这会更好地告诉我们这里到底发生了什么。我的猜测是您的 TypeScript 设置正在从您的 index.js 生成一个 CommonJS 模块,因此它生成了一个 require('nanoid') 这是不合法的,因为 nanoid 是一个 ESM 模块。所以,也许您的 TypeScript 编译器配置有误。但是,这只是一个猜测。查看生成的 JS 文件会告诉您更多信息。

标签: typescript es6-modules nanoid


【解决方案1】:

出现错误“[ERR_REQUIRE_ESM]: require() not supported”是因为您正在导入的包已转换为仅 ESM 包,这意味着无法再使用 require() 导入该包。 使用 npm i nanoid@2.1.11

【讨论】:

    【解决方案2】:

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

    nanoid 文档没有具体说明这一点,但我只是想了想并尝试了一下,它起作用了

    我希望这对其他人有帮助

    【讨论】:

      【解决方案3】:

      如果您使用另一个版本的nanoid,它会起作用。例如:

      npm uninstall nanoid
      npm install nanoid@3.3.4
      

      如果没有,请尝试根据 to this 更改您的一些 tsconfig.json

      【讨论】:

        猜你喜欢
        • 2021-12-05
        • 2022-08-23
        • 2021-12-07
        • 2022-11-09
        • 1970-01-01
        • 2021-11-03
        • 1970-01-01
        • 2023-01-28
        • 2022-11-10
        相关资源
        最近更新 更多