Node.js WebSocket库的同构库选取
我得到一个错误:Node.js WebSocket库的同构库选取,node.js,browser,ecmascript-5,Node.js,Browser,Ecmascript 5,我得到一个错误: import { default as WebSocket } from 'ws'; const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined'; const url = ...; let webSocket; const isBrowser ? // Browser. (webSocket = new global.Web
import { default as WebSocket } from 'ws';
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
const url = ...;
let webSocket;
const isBrowser
? // Browser.
(webSocket = new global.WebSocket(url))
: // Node.js.
(webSocket = new WebSocket(url));
如果我将其更改为window.WebSocket
src/client.ts:155:48 - error TS2339: Property 'WebSocket' does not exist on type 'Global'.
155 ? (webSocket = new global.WebSocket(url))
我正在尝试创建一个同构库,它将在Node.js和浏览器中工作。如何简单地做到这一点?我几乎是正确的:我需要使用
globalThis.WebSocket
而不是global.WebSocket
src/client.ts:156:20 - error TS2740: Type 'WebSocket' is missing the following properties from type 'WebSocket': ping, pong, terminate, on, and 14 more.
156 (webSocket = new window.WebSocket(url))