[英]cant get ES modules to work with import or require
我正在构建一个基于命令行的应用程序,并使用 require 来链接各种文件和节点模块。 我以前使用 Require 没有任何问题,现在我得到的只是错误。
要求错误:
错误 [ERR_REQUIRE_ESM]: 不支持 ES Module./lib/departments.cjs 的 require(),而是将 ./lib/departments.cjs 中的inquirer.js 的 require 更改为在所有 CommonJS 模块中都可用的动态 import() .
在此之后,我尝试了多种方法让它再次工作,但没有运气所以我尝试切换到导入。 当我切换到导入时,我收到了这条消息:
SyntaxError: 不能在模块外使用 import 语句
我尝试将type: "module"添加到我的 package.json 文件中,但我不知道我是否将它放在错误的位置或什么地方。 我的 JSON 文件看起来像这样
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "server.js",
"directories": {
"lib": "lib"
},
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"repository": {
"type": "git",
"url": "git+https://.git"
},
"author": "",
"license": "MIT",
"bugs": {
"url": "https://issues"
},
"homepage": "https://#readme",
"dependencies": {
"console.table": "^0.10.0",
"dotenv": "^16.0.2",
"express": "^4.18.1",
"inquirer": "^9.1.1",
"mysql2": "^2.3.3",
"node-fetch": "^2.6.7"
}
}
好像您正在为您的 js 文件使用.cjs
扩展名, cjs
是一个不支持import
的 commonJS 文件。 您需要使用动态导入。
值得一提的是,使用cjs
的 require() function 无法导入 ES 模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.