你会如何修复一个 'ERR_REQUIRE_ESM' 错误?

8

我正在尝试使用chalk npm。 我的代码是:

     const chalk = require('chalk');

          console.log(
          chalk.green('All sytems go') +
          chalk.orange('until').underline +
          chalk.black(chalk.bgRed('an error occurred'))
           );

当我输入 node main.js 时,在我的终端中会收到这个错误。

Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/ezell/Documents/CodeX/NPM/node_modules/chalk/source/index.js from /Users/ezell/Documents/CodeX/NPM/main.js not supported.
Instead change the require of index.js in /Users/ezell/Documents/CodeX/NPM/main.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/Users/ezell/Documents/CodeX/NPM/main.js:1:15) {
  code: 'ERR_REQUIRE_ESM'
}
4个回答

11

我遇到了同样的“ERR_REQUIRE_ESM”错误,针对nanoid:^4.0.0版本存在多种解决方法:

1)使用 fix esm 模块 https://www.npmjs.com/package/fix-esm,并像这样导入该模块:

const someModule = require("fix-esm").require("some-module");

2)使用动态导入,如下所示:

import('nanoid') 
.then((res)=>{ console.log(res) })         
.catch((err)=>{ console.log(err) });

请确保在上述两种情况下,package.json文件中没有type: "module"字段,否则会出现"TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension"错误。

3)将模块版本降级到稳定的旧版本,例如,在我的情况下,当我将nanoid版本降级到以下版本时问题得到解决:

"nanoid": "^3.1.22"

1
那是对我来说最有用的答案。谢谢你的分享。 - Ikem Krueger

5
最新版本的 Chalk 只与 ESM 模块兼容,因此希望您使用 import 而不是 require() 加载它。
从文档中可以看到:

重要提示:Chalk 5 是 ESM。如果您想在 TypeScript 或构建工具中使用 Chalk,则现在可能需要使用 Chalk 4。阅读更多

所以,您可以选择:
  1. 将项目切换为 ESM 模块,并使用 import 而不是 require() 加载最新版本的 Chalk。

  2. 安装可以使用 require() 的 Chalk 版本 4。

  3. 使用相当新的 Node.JS 版本,您可以使用动态导入将 ESM 模块加载到您的 CommonJS 模块中:const chalk = await import('chalk');


3
解决方案,这是因为您需要先使用当前稳定版本2.x:
npm uninstall -D node-fetch

之后:
npm install node-fetch@2

这应该可以正常工作。

我真的希望这个“解决方案”能有更多的解释。 - Professor Tom

3

您需要切换到使用 import 关键字,因为 Chalk 5 仅支持 ESM 模块。


因此,要修复您的代码以适应这些更改,您需要...

  1. Edit your package.json file to allow ESM imports. Add the following in your package.json file:

    {
      "type": "module"
    }
    
  2. Load Chalk with the import keyword, as so:

    import chalk from "chalk";
    
如果您想使用require(),则需要降级到Chalk 4。按照以下步骤进行降级。
  1. Replace your existing chalk key with the following in your package.json file:

    {
      "dependencies": {
        "chalk": "4.1.2"
      }
    }
    
  2. Then, run the following command to install Chalk from your package.json file. Make sure to run this in the directory in which your package.json file is in!

    $ npm install
    
  3. Use the require() statement like normal.

    const chalk = require("chalk");
    

总之,您可以做以下两件事情。

  • 继续使用Chalk 5,并更新import语句。
  • 降级到Chalk 4,并保留require()语句。

1
非常感谢!添加了从 "chalk" 导入 chalk 和 "type": "module" 就可以了!! - Tarneka Ezell
请添加以下内容。好的,添加到文件末尾? - serge
@serge 不管在哪里都没关系。 - Arnav Thorat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接