解决 Laravel Echo 对 window 对象的依赖
Laravel Echo 项目被用于广播客户端代码,但由于其默认依赖 window 对象全局获取 Pusher 类,无法通过前端测试自动化(即便使用了 jsdom),也对其他无 window 对象的平台(比如小程序)造成一些麻烦。
官方给出的例子中有使用现成 Pusher 实例的方式:
广播系统《Laravel 11 中文文档》
根据这里的启发我翻了一下 Laravel Echo 的源码:
github.com/laravel/echo/blob/maste...
/**
* Create a fresh Pusher connection.
*/
connect(): void {
if (typeof this.options.client !== 'undefined') {
this.pusher = this.options.client;
} else if (this.options.Pusher) {
this.pusher = new this.options.Pusher(this.options.key, this.options);
} else {
this.pusher = new Pusher(this.options.key, this.options);
}
}
发现其可以通过 options.Pusher 属性获取引入的 Pusher 类。
官方文档虽没给出这种用法,但我们可以采用如下代码进行 Echo 对象的实例化来解决对 window 对象的依赖问题:
import Pusher from "pusher-js"
import Echo from "laravel-echo"
/**
* 初始化 Laravel Echo
*/
const echo = new Echo({
broadcaster: 'reverb',
key: import.meta.env.VITE_REVERB_APP_KEY,
wsHost: import.meta.env.VITE_REVERB_HOST,
wsPort: import.meta.env.VITE_REVERB_PORT,
wssPort: import.meta.env.VITE_REVERB_PORT,
forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
enabledTransports: ['ws', 'wss'],
authEndpoint: import.meta.env.VITE_REVERB_AUTH_ENDPOINT,
auth: {
headers: {
Authorization: authenticationStore.authentication,
},
},
Pusher,
})