> 技术文档 > uniapp打包的app连接RabbitMQ的MQTT实战demo_mqtt连接失败:, typeerror: ws is not a constructor

uniapp打包的app连接RabbitMQ的MQTT实战demo_mqtt连接失败:, typeerror: ws is not a constructor

uniapp的微信小程序或者app来连接websocket、mqtt都是开发者的痛,一言难尽。

服务端使用的是RabbitMQ的MQTT,本文描述uniapp打包的app客户端如何连接MQTT,并附上完整Demo代码。

页面截图

目录

页面截图

常见报错

常见报错:白屏 white screen cause create instanceContext failed,check js stack ->Uncaught ReferenceError: process is not defined

常见报错:Rollup failed to resolve import \"mqtt/dist/mqtt.js\" from

常见报错:white screen cause create instanceContext failed,check js stack ->Uncaught TypeError: Cannot read property \'language\' of undefined

常见报错:TypeError: WS is not a constructor

常见报错:TypeError: socketTask.onOpen is not a function

1.安装指定版本mqtt

2.引入方式

3.协议头

4.修改源码node_modules/mqtt/dist/mqtt.js

5.解决修改源码后install覆盖修改的问题

完整代码


常见报错

常见报错:白屏 white screen cause create instanceContext failed,check js stack ->Uncaught ReferenceError: process is not defined

这个错误是由于 MQTT.js 库中使用了 Node.js 特有的 process 全局变量,而浏览器/UniApp 环境中不存在这个变量导致的。直接 import mqtt from \'mqtt\' 导入的是 Node.js 版本的 MQTT.js。这个版本默认依赖 Node.js 环境变量(如 process)

需要将import mqtt from \"mqtt\" 换成import mqtt from \'mqtt/dist/mqtt.js\'

常见报错:Rollup failed to resolve import \"mqtt/dist/mqtt.js\" from

19:04:47.757 This is most likely unintended because it can break your application at runtime.

19:04:47.757 If you do want to externalize this module explicitly add it to

19:04:47.757 `build.rollupOptions.external`

这个错误表明 Vite 在构建过程中无法解析 mqtt/dist/mqtt.js 模块

如果你在调试app环境,需要将mqtt的版本降到3.0.0

常见报错:white screen cause create instanceContext failed,check js stack ->Uncaught TypeError: Cannot read property \'language\' of undefined

这个错误说明MQTT未能正确初始化

uniapp需要安装能正确识别的版本3.0.0

常见报错:TypeError: WS is not a constructor

这个错误通常发生在尝试使用 MQTT.js 时,WebSocket 连接初始化失败。也是uniapp的特殊环境引起的。

解决:需要把ws协议头换成wx

常见报错:TypeError: socketTask.onOpen is not a function

修改源码:node_modules/mqtt/dist/mqtt.js

注意,在app端,修改的是wx.connectSocket

 socketTask = wx.connectSocket({ url: url, protocols: websocketSubProtocol, success:()=>{}//增加这行 })

以下是完整集成过程: