如何解决Bazel + Angular + SocketIO V3原因:未捕获的TypeError:XMLHttpRequest不是构造函数
我想将socket.io-client(v3)添加到我的Angular应用程序中。我使用Bazel来构建和运行Angular。不幸的是,运行ts_devserver时,我在浏览器控制台中收到此错误:
ERROR Error: Uncaught (in promise): TypeError: XMLHttpRequest is not a constructor
TypeError: XMLHttpRequest is not a constructor
at ts_scripts.js?v=80175740:15476
at Object.14.../globalThis (ts_scripts.js?v=80175740:15480)
使用Socket.IO v2时遇到相同的问题。 但是old solution不再起作用。
这一次,甚至没有在生产环境中运行Angular应用。
最低繁殖量
您可以自己尝试:flolu/angular-bazel-socketio3-issue
只需运行yarn install
,然后运行yarn dev
。错误是在浏览器控制台中的http:// localhost:4200。
请注意,在位于http:// localhost:4000的yarn prod
的{{3}}中运行应用程序时,还会出现另一个错误:
ERROR Error: Uncaught (in promise): ReferenceError: Cannot access 'e' before initialization
ReferenceError: Cannot access 'e' before initialization
at home.module-7db83ffb.js:formatted:953
解决方法
我不知道为什么Sebastian's solution不再起作用。据我所知,engine.io-client
并没有太大变化,它仍然有一些对"xmlhttprequest-ssl"
的要求,应该用"../xmlhttprequest"
来代替。这就是他在该脚本中所做的。但是我的node_modules在该脚本之后没有更改,也许我做错了。
但是无论如何,对我有用的就是通过patch-package
做同样的事情(我更习惯于修补node_modules)。
对于生产捆绑包,我只是在删除了导致生产错误的多余需求后设法使其正常工作。
也就是说,这是最后一个补丁(将其放入patches/engine.io-client+4.0.2.patch
中):
diff --git a/node_modules/engine.io-client/lib/transports/index.js b/node_modules/engine.io-client/lib/transports/index.js
index 923223d..1ec2668 100755
--- a/node_modules/engine.io-client/lib/transports/index.js
+++ b/node_modules/engine.io-client/lib/transports/index.js
@@ -1,4 +1,4 @@
-const XMLHttpRequest = require("xmlhttprequest-ssl");
+const XMLHttpRequest = require("../xmlhttprequest");
const XHR = require("./polling-xhr");
const JSONP = require("./polling-jsonp");
const websocket = require("./websocket");
diff --git a/node_modules/engine.io-client/lib/transports/polling-xhr.js b/node_modules/engine.io-client/lib/transports/polling-xhr.js
index 9988b02..a2ff168 100755
--- a/node_modules/engine.io-client/lib/transports/polling-xhr.js
+++ b/node_modules/engine.io-client/lib/transports/polling-xhr.js
@@ -1,6 +1,6 @@
/* global attachEvent */
-const XMLHttpRequest = require("xmlhttprequest-ssl");
+const XMLHttpRequest = require("../xmlhttprequest");
const Polling = require("./polling");
const Emitter = require("component-emitter");
const { pick } = require("../util");
@@ -15,7 +15,6 @@ const debug = require("debug")("engine.io-client:polling-xhr");
function empty() {}
const hasXHR2 = (function() {
- const XMLHttpRequest = require("xmlhttprequest-ssl");
const xhr = new XMLHttpRequest({ xdomain: false });
return null != xhr.responseType;
})();
此外,不要忘记在安装后步骤中添加补丁程序包:
"postinstall": "patch-package && ngcc"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。