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

VSCode扩展中集成SignalR报错:requireFunc is not a function

在VSCode扩展中集成SignalR遇到requireFunc is not a function错误的解决办法

问题描述

在VSCode扩展中按照官方文档集成SignalR,package.json依赖如下:

"dependencies": {
    "@microsoft/signalr": "^6.0.8",
    "@taqueria/protocol": "^0.12.0",
    "cli-table3": "^0.6.2",
    "comment-json": "^4.1.1",
    "node-fetch": "^3.2.10",
    "promise-memoize": "^1.2.1",
    "rambda": "^7.0.1",
    "rxjs": "^7.5.6",
    "semver": "^7.3.7"
}

运行时抛出错误:requireFunc is not a function,错误代码位于node_modules/@microsoft/signalr/src/HttpConnection.ts:

if (Platform.isNode && typeof require !== "undefined") {
    // In order to ignore the dynamic require in webpack builds we need to do this magic
    // @ts-ignore: TS doesn't know about these names
    const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
    webSocketModule = requireFunc("ws");
    eventSourceModule = requireFunc("eventsource");
}

调试确认__webpack_require__、__non_webpack_require__和require三个变量均未定义。

解决方案

方案1:添加依赖并配置webpack externals

  1. 安装SignalR依赖的Node.js模块:
npm install ws eventsource --save
  1. 在webpack.config.js中添加externals配置,让webpack不打包这两个模块,保留原生require加载逻辑:
module.exports = {
    // 其他已有配置...
    externals: {
        "ws": "commonjs ws",
        "eventsource": "commonjs eventsource"
    }
};

方案2:使用SignalR浏览器构建版本

直接导入SignalR的浏览器适配版本,绕过Node.js环境的动态require逻辑:

import * as signalR from "@microsoft/signalr/dist/browser/signalr.min.js";

方案3:通过webpack DefinePlugin暴露require变量

在webpack配置中注入require变量,让SignalR的Node.js适配代码能正常获取:

const webpack = require('webpack');

module.exports = {
    // 其他已有配置...
    plugins: [
        new webpack.DefinePlugin({
            require: 'require'
        })
    ]
};

原因说明

VSCode扩展默认使用webpack打包,打包过程中会将Node.js环境的require等变量封装或移除,导致SignalR的Node.js适配代码无法找到这些变量,进而无法动态加载ws和eventsource模块,引发错误。上述方案通过不同方式让SignalR能正确获取到所需的模块加载能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:03:21