问题来自于
engine.io-client
,它是
socket.io-client
内部使用的:
当
socket.io-client
作为UMD模块构建时触发。
"@npm//socket.io-client:socket.io-client__umd",
在
BUILD.bazel
文件中,
engine.io-client/package.json
的
browser
键:
"browser": {
"ws": false,
"xmlhttprequest-ssl": "./lib/xmlhttprequest.js"
},
似乎被忽略。
因此,在UMD构建中,node_modules/engine.io-client/lib/transports/*.js
中的 require('xmlhttprequest-ssl')
语句仍然存在。由于 xmlhttprequest-ssl
用于无头Node环境并且在浏览器中不起作用,因此会导致错误。
我找不到这种行为的原因/问题,但我找到了一个解决方案(不应视为解决方法):
使用 postinstall
脚本重写 engine.io-client
:
- 安装
shelljs
包: yarn add -D shelljs
- 将
package.json
中的 postinstall
更新为:"postinstall": "node --preserve-symlinks --preserve-symlinks-main ./postinstall-patches.js && ngcc"
- 将以下代码放入项目根目录下的
postinstall-patches.js
中:
try {
require.resolve('shelljs');
} catch (e) {
console.warn(
`Running postinstall-patches.js script in an external repository requires --preserve-symlinks-main node flag introduced in node 10.2.0. ` +
`Current node version is ${process.version}. Node called with '${process.argv.join(' ')}'.`);
process.exit(0);
}
const {set, cd, sed, ls} = require('shelljs');
const path = require('path');
const log = console.info;
log('===== about to run the postinstall-patches.js script =====');
set('-e');
set('-v');
cd(__dirname);
log('\n# patch engine.io-client: rewriting \'xmlhttprequest-ssl\' to browser shim');
ls('node_modules/engine.io-client/lib/transports/*.js').forEach(function (file) {
sed('-i', '\'xmlhttprequest-ssl\'', '\'../xmlhttprequest\'', file);
});
log('===== finished running the postinstall-patches.js script =====');
(灵感来源: https://bazelbuild.github.io/rules_nodejs/#patching-the-npm-packages,其中链接到示例https://github.com/angular/angular/blob/master/tools/postinstall-patches.js)
yarn install
(安装依赖)
yarn dev
(运行项目)
我将在几分钟内向您的GitHub存储库提交拉取请求。
可能的替代方案,但无法让它们工作:
- 使用
socket.io-client/dist/socket.io.js
,但需要额外的“UMD shim”,因为它似乎是一个“匿名UMD”模块,或者
- 一些
npm_umd_bundle
魔法
有关这两种方法的更多信息,请参见每个新的npm依赖项都需要独特的方法来将其添加到ts_devserver #1055中在bazelbuild/rules_nodejs
问题。