const chalk = require("chalk");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module P:Back End DevelopmentNPM_modulesnode_moduleschalksourceindex.js from P:Back End DevelopmentNPM_modulesindex.js not supported.
Instead change the require of P:Back End DevelopmentNPM_modulesnode_moduleschalksourceindex.js in P:Back End DevelopmentNPM_modulesindex.js to a dynamic import() which is available in all CommonJS modules.
at Object. (P:Back End DevelopmentNPM_modulesindex.js:1:15) {
code: 'ERR_REQUIRE_ESM'
}
I am expected a Blue Color code "Hello world">
如错误提示,chalk
包不能包含在CommonJS中文件与require()
方法,因为它是一个ES模块.
要导入ES模块,您需要更改package.json
文件,在其中添加:
"type": "module"
之后,您需要使用import
语句导入所有包,如下面的示例所示:
import chalk from 'chalk';
如果,出于某种原因,你不想改变你的package.json
或者你必须用CommonJS导入你的包,您可以使用此方法导入chalk:
var chalk;
(async function () {
chalk = await import("chalk");
})();
但是你需要确保粉笔包在完全导入之前不会被使用。