nodejs的版本是12.17.0 在练习一个自定义cli的过程中,遇到了以下问题:
安装的依赖有如下:
"dependencies": {
"chalk": "^5.0.1",
"clear": "^0.1.0",
"commander": "^9.2.0",
"download-git-repo": "^3.0.2",
"figlet": "^1.5.2",
"handlebars": "^4.7.7",
"open": "^8.4.0",
"ora": "^6.1.0"
}
PS E:\node-proj\vue-auto-router-cli> kkb init test
internal/modules/cjs/loader.js:1154
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: E:\node-proj\vue-auto-router-cli\node_modules\chalk\source\index.js
require() of ES modules is not supported.
require() of E:\node-proj\vue-auto-router-cli\node_modules\chalk\source\index.js from E:\node-proj\vue-auto-router-cli\lib\init.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from E:\node-proj\vue-auto-router-cli\node_modules\chalk\package.json.
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1154:13)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Module.require (internal/modules/cjs/loader.js:1026:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object.<anonymous> (E:\node-proj\vue-auto-router-cli\lib\init.js:4:15)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14) {
code: 'ERR_REQUIRE_ESM'
}
PS E:\node-proj\vue-auto-router-cli>
网上能搜到的方法都用了 统统没用 欢迎有经验的玩家支招
可能是nodejs版本过低导致的,尝试下这两个版本两个版本来进行安装:v14和v16(n为node包版本管理工具)
sudo npm install -g n
sudo n 14 # 切换到14版本
node-v
sudo npm i
sudo n 16 # 切换到16版本
node-v
sudo npm i
你的代码没有给出有效部分,我觉得是你使用了require的方式去引用了chalk这个模块,但是最新版的chalk是只支持esm规范的,所以要么你降低chalk版本,要么你使用import导入。如果有用,望采纳
你写错位置了吧。require是node的用法。用webpack的话,运行的东西不是写到这里的。应该是写到vue.config.js或者webpack的配置文件中
1.通过报错信息是 node 版本过高造成的 先降版本
但是出现Error [ERR_REQUIRE_ESM]: Must use import to load ES Module的错误,在网上找了很就才解决这个问题,原来是node的版本问题,一开始我使用的是最新的node版本12.16.0版本,将node的版本降低到12.10.0版本就可以解决
原文链接:https://blog.csdn.net/qq_24698097/article/details/104750848
应该是你的js语法有问题,按下图将require改为import关键字试试