使用discord.js执行npm run test时出现第三方文件语法错误
问题:discord.js依赖文件触发SyntaxError: Unexpected token '.'错误
问题场景
在Node.js环境中使用discord.js模块,执行npm run test(实际脚本为node .)时,在未手动创建的依赖文件discord.js/src/client/BaseClient.js第45行触发语法错误,错误提示为SyntaxError: Unexpected token '.'。
完整报错栈
D:\GhulamMuhammad\Programming\WebDev\Node.js\NeuralNode-Bot\node_modules\discord.js\src\client\BaseClient.js:45 userAgentAppendix: options.rest?.userAgentAppendix ^ SyntaxError: Unexpected token '.' ←[90m at Object.compileFunction (vm.js:344:18)←[39m ←[90m at wrapSafe (internal/modules/cjs/loader.js:1048:15)←[39m ←[90m at Module._compile (internal/modules/cjs/loader.js:1082:27)←[39m ←[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1138:10)←[39m ←[90m at Module.load (internal/modules/cjs/loader.js:982:32)←[39m ←[90m at Function.Module._load (internal/modules/cjs/loader.js:875:14)←[39m ←[90m at Module.require (internal/modules/cjs/loader.js:1022:19)←[39m ←[90m at require (internal/modules/cjs/helpers.js:72:18)←[39m at Object.<anonymous> (D:\GhulamMuhammad\Programming\WebDev\Node.js\NeuralNode-Bot\node_modules\←[4mdiscord.js←[24m\src\index.js:6:22) ←[90m at Module._compile (internal/modules/cjs/loader.js:1118:30)←[39m npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! NeuralNode-Bot@1.0.0 test: `node .` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the NeuralNode-Bot@1.0.0 test script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\SAAD\AppData\Roaming\npm-cache\_logs\2024-03-14T14_49_46_164Z-debug.log D:\GhulamMuhammad\Programming\WebDev\Node.js\NeuralNode-Bot>
原因分析
报错代码中的?.是可选链操作符,属于ES2020新增的语法特性。你的Node.js版本过低,不支持该语法,导致discord.js的源码无法被正常编译执行。目前discord.js v14及以上版本要求Node.js最低版本为v16.9.0,若你的Node.js版本低于此要求,就会出现该错误。
解决步骤
- 检查当前Node.js版本:执行命令
node -v - 升级Node.js:如果版本低于v16.9.0,升级到符合要求的版本(推荐使用LTS版本如v18或v20)
- 重新安装依赖:删除项目根目录下的
node_modules文件夹和package-lock.json文件,执行npm install - 重新测试:运行
npm run test验证问题是否解决
内容的提问来源于stack exchange,提问作者pomegrenade
相关产品推荐
相关产品推荐

