运行Slack API相关JS文件时出现ERR_REQUIRE_ESM错误求助
解决Node.js 18环境下Slack Bot的ERR_REQUIRE_ESM错误
你在Node.js 18环境下开发Slack Bot时遇到了ERR_REQUIRE_ESM错误,核心原因是依赖的@slack包及axios已采用纯ESM格式,而你使用的第三方esm加载器与Node.js原生ESM支持产生冲突。
现有代码
index.js
require = require("esm")(module/*, options*/) module.exports = require("./app.js")
app.js
import { RTMClient } from "@slack/rtm-api"; import { SLACK_0AUTH_TOKEN } from './constants.js'; const rtm = new RTMClient(SLACK_0AUTH_TOKEN); rtm.start().catch(console.error); rtm.on('ready', async () => { console.log('Bot is now online'); });
package.json
{ "name": "slackapi", "version": "1.0.0", "description": "Slack Bot Testing", "main": "src", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node ." }, "author": "", "license": "ISC", "dependencies": { "@slack/rtm-api": "^7.0.0", "@slack/web-api": "^7.3.1", "esm": "^3.2.25" } }
错误信息
D:\Desktop\SlackAPI\node_modules\@slack\web-api\dist\WebClient.js:1 Error [ERR_REQUIRE_ESM]: require() of ES Module D:\Desktop\SlackAPI\node_modules\axios\index.js not supported. Instead change the require of index.js in null to a dynamic import() which is available in all CommonJS modules. at Object.<anonymous> (D:\Desktop\SlackAPI\node_modules\@slack\web-api\dist\WebClient.js:63:33) at Object.<anonymous> (D:\Desktop\SlackAPI\node_modules\@slack\web-api\dist\index.js:22:19) at Object.<anonymous> (D:\Desktop\SlackAPI\node_modules\@slack\rtm-api\dist\RTMClient.js:12:19) at Object.<anonymous> (D:\Desktop\SlackAPI\node_modules\@slack\rtm-api\dist\index.js:5:19) at Generator.next (<anonymous>) at Object.<anonymous> (D:\Desktop\SlackAPI\src\app.js:1) at Generator.next (<anonymous>) at Object.<anonymous> (D:\Desktop\SlackAPI\src\index.js:4:18) { code: 'ERR_REQUIRE_ESM' }
解决方案
Node.js 18原生支持ES模块,无需依赖第三方esm加载器,按以下步骤修改:
移除esm依赖
执行卸载命令:npm uninstall esm修改package.json启用原生ESM
添加"type": "module"字段,同时更新入口和启动脚本配置:{ "name": "slackapi", "version": "1.0.0", "description": "Slack Bot Testing", "type": "module", "main": "src/app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node src/app.js" }, "author": "", "license": "ISC", "dependencies": { "@slack/rtm-api": "^7.0.0", "@slack/web-api": "^7.3.1" } }删除index.js文件
不再需要这个中间加载器文件,直接以app.js作为项目入口。确认constants.js的导出格式
确保常量文件使用ES模块导出语法:export const SLACK_0AUTH_TOKEN = "你的Slack授权令牌";启动项目
执行启动命令:npm start
完成以上修改后,项目将使用Node.js原生ESM加载模块,解决与@slack包、axios的兼容性问题,Bot应该能正常启动并输出Bot is now online。
内容的提问来源于stack exchange,提问作者Century Tuna
相关产品推荐
相关产品推荐

