You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel+Vue3项目npm run build后window.Pusher不是构造函数问题

Laravel + Vue3 + Vite构建生产版本后出现window.Pusher is not a constructor错误

问题详情

在Laravel + Vue3项目中使用Vite、Laravel Echo和pusher-js,npm run dev开发环境运行正常,但执行npm run build构建生产版本后,浏览器控制台抛出错误:Uncaught (in promise) TypeError: window.Pusher is not a constructor。开发环境中Pusher是正常的构造函数,生产构建后却变成普通对象,控制台输出Object { … } (not a constructor)。

现有代码

bootstrap.js

if (typeof window !== 'undefined') {
    window.axios = axios;
    window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}

import './echo.js';

echo.js

import Pusher from 'pusher-js';

if (typeof window !== 'undefined') {
    console.log('Pusher', Pusher);
    window.Pusher = Pusher;

    window.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 ?? 80,
        wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,
        forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
        enabledTransports: ['ws', 'wss'],
    });
}

已尝试的无效方案

  • 将代码包裹在if (typeof window !== 'undefined')判断中
  • 使用动态导入import('pusher-js').then(...)
  • 访问动态导入的module.default

解决方案

方案1:修正Pusher构造函数的获取逻辑

生产构建时Vite的模块处理可能导致pusher-js的导出形式变化,需明确获取构造函数:
修改echo.js中的导入与赋值逻辑:

import Pusher from 'pusher-js';

if (typeof window !== 'undefined') {
    // 兼容ES模块导出的差异,确保拿到构造函数
    const PusherConstructor = typeof Pusher === 'function' ? Pusher : Pusher.default;
    window.Pusher = PusherConstructor;

    window.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 ?? 80,
        wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,
        forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
        enabledTransports: ['ws', 'wss'],
    });
}

方案2:配置Vite优化依赖

在vite.config.js中添加依赖优化配置,避免Vite对pusher-js和laravel-echo进行过度tree-shaking:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    plugins: [
        laravel({
            input: 'resources/js/app.js',
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
    // 添加以下优化配置
    optimizeDeps: {
        include: ['pusher-js', 'laravel-echo']
    }
});

方案3:调整pusher-js版本

部分新版本pusher-js的ESM导出存在兼容性问题,可尝试降级到稳定版本(如7.6.0):

npm install pusher-js@7.6.0

内容的提问来源于stack exchange,提问作者philip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 07:19:53