Tar*_*ell 12 node.js npm chalk
我正在尝试使用 chalk npm。我的代码是:
const chalk = require('chalk');
console.log(
chalk.green('All sytems go') +
chalk.orange('until').underline +
chalk.black(chalk.bgRed('an error occurred'))
);
Run Code Online (Sandbox Code Playgroud)
当我输入 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'
}
Run Code Online (Sandbox Code Playgroud)
viv*_*rma 13
我对 nanoid:^4.0.0 遇到了相同的“ERR_REQUIRE_ESM”错误,并且有多种方法可以解决此错误:-
1)使用 fix esm https://www.npmjs.com/package/fix-esm模块并像这样导入模块:
const someModule = require("fix-esm").require("some-module");
Run Code Online (Sandbox Code Playgroud)
2)使用动态导入如下图:
import('nanoid')
.then((res)=>{ console.log(res) })
.catch((err)=>{ console.log(err) });
Run Code Online (Sandbox Code Playgroud)
只需确保在上述两种情况下 package.json 中没有 type:"module" 字段,否则您会收到“TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension”错误
3)将模块版本降级到稳定的旧版本,例如在我的例子中,当我将 nanoid 版本降级到:
"nanoid": "^3.1.22"
Run Code Online (Sandbox Code Playgroud)
最新版本的Chalk仅与 ESM 模块兼容,因此希望您使用import, 而不是来加载它require()。
来自文档:
重要提示:第 5 部分是 ESM。如果您想将 Chalk 与 TypeScript 或构建工具一起使用,您现在可能需要使用 Chalk 4。阅读更多。
所以,你的选择是:
将您的项目切换到 ESM 模块并加载最新版本的 Chalk,而import不是require().
安装 Chalk 版本 4,它可以与require().
使用最新版本的 Node.JS,您可以使用动态导入将 ESM 模块加载到 CommonJS 模块中:const chalk = await import('chalk');
您需要切换到使用import关键字,因为 Chalk 5 仅支持 ESM 模块。
因此,要修复代码以适应这些更改,您需要......
编辑您的package.json文件以允许 ESM 导入。在您的文件中添加以下内容package.json:
{
"type": "module"
}
Run Code Online (Sandbox Code Playgroud)
使用import关键字加载 Chalk,如下所示:
import chalk from "chalk";
Run Code Online (Sandbox Code Playgroud)
但是,如果您想使用require(),则需要降级到 Chalk 4。请按照以下步骤降级。
将现有chalk密钥替换为文件中的以下内容package.json:
{
"dependencies": {
"chalk": "4.1.2"
}
}
Run Code Online (Sandbox Code Playgroud)
然后,运行以下命令从您的文件安装 Chalk package.json。确保在package.json文件所在的目录中运行它!
$ npm install
Run Code Online (Sandbox Code Playgroud)
require()像平常一样使用该语句。
$ npm install
Run Code Online (Sandbox Code Playgroud)
总而言之,这是您可以做的两件事。
import陈述。require()陈述。| 归档时间: |
|
| 查看次数: |
57117 次 |
| 最近记录: |