构建后运行WhatsApp-web.js应用时Puppeteer报moduleRaid2未定义错误
解决WhatsApp-web.js构建后Puppeteer的moduleRaid2未定义错误
使用WhatsApp-web.js v1.23.0开发的依赖Puppeteer的应用,本地运行正常,但构建后启动时抛出ReferenceError: moduleRaid2 is not defined错误,更换本地Chrome运行也无法解决。以下是针对性解决方案:
解决方案
1. 配置构建工具排除WhatsApp-web.js和Puppeteer的打包
构建工具(如Webpack、Vite)的Tree Shaking可能误删WhatsApp-web.js内部依赖的moduleRaid2脚本,需将这两个包设为外部依赖,避免被打包进bundle:
Webpack配置(webpack.config.js)
module.exports = { // 其他配置项... externals: { 'whatsapp-web.js': 'require("whatsapp-web.js")', 'puppeteer': 'require("puppeteer")' } };
Vite配置(vite.config.js)
export default { build: { rollupOptions: { external: ['whatsapp-web.js', 'puppeteer'] } } };
2. 动态获取Puppeteer的可执行文件路径
构建后项目结构变化,写死的executablePath可能失效,改用Puppeteer提供的executablePath()方法动态获取路径:
import puppeteer from 'puppeteer'; import { Client } from 'whatsapp-web.js'; const client = new Client({ puppeteer: { headless: true, args: [ '--disable-gpu', '--disable-setuid-sandbox', '--no-sandbox', '--no-zygote' ], executablePath: puppeteer.executablePath(), }, takeoverOnConflict: true, takeoverTimeoutMs: 10, authStrategy, });
3. 降级WhatsApp-web.js版本
v1.23.0版本可能存在与构建工具不兼容的问题,尝试降级到v1.22.2:
npm install whatsapp-web.js@1.22.2
验证步骤
修改配置或版本后,重新执行构建命令,运行dist目录下的应用,确认错误是否消失。
内容的提问来源于stack exchange,提问作者ranggaalk
相关产品推荐
相关产品推荐

