首次开发JavaScript Discord Bot遇import语法错误求助
解决Discord Bot启动时的
SyntaxError: Cannot use import statement outside a module错误 这个报错的核心原因是:Node.js默认将.js文件识别为CommonJS模块,而你在代码里使用了ES模块的import语法,两种模块规范不兼容导致报错。下面提供两种可行的解决办法:
方法一:将项目切换为ES模块
- 在项目根目录的
package.json文件中添加"type": "module"字段,示例如下:
{ "name": "your-bot-project", "version": "1.0.0", "type": "module", "dependencies": { "discord.js": "^14.14.1", "dotenv": "^16.4.5" } }
- 移除代码中的
require语法(ES模块不支持require),修改后的完整代码:
import dotenv from "dotenv"; dotenv.config(); import { Client, GatewayIntentBits, ButtonBuilder, ButtonStyle, ModalBuilder, TextInputBuilder, TextInputStyle } from "discord.js"; const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers, GatewayIntentBits.DirectMessages ], }); client.login(process.env.TOKEN);
方法二:改用CommonJS语法
直接把所有import替换为require,保持Node.js默认的CommonJS模块规范,修改后的代码:
require("dotenv").config(); const { Client, GatewayIntentBits, ButtonBuilder, ButtonStyle, ModalBuilder, TextInputBuilder, TextInputStyle } = require("discord.js"); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers, GatewayIntentBits.DirectMessages ], }); client.login(process.env.TOKEN);
额外提示
.env文件中的配置建议去掉引号,写成TOKEN=discord bot token,避免潜在的解析异常。
内容的提问来源于stack exchange,提问作者WolfDatka
相关产品推荐
相关产品推荐

