WebSocket库的同构库摘取
Isomorphic library picking of WebSocket library
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));
我收到错误:
src/client.ts:155:48 - error TS2339: Property 'WebSocket' does not exist on type 'Global'.
155 ? (webSocket = new global.WebSocket(url))
如果我将其更改为 window.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))
我正在尝试创建一个可以在 Node.js 和浏览器中运行的同构库。如何简单地做到这一点?
我几乎是正确的:我需要使用 globalThis.WebSocket
而不是 global.WebSocket
。
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));
我收到错误:
src/client.ts:155:48 - error TS2339: Property 'WebSocket' does not exist on type 'Global'.
155 ? (webSocket = new global.WebSocket(url))
如果我将其更改为 window.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))
我正在尝试创建一个可以在 Node.js 和浏览器中运行的同构库。如何简单地做到这一点?
我几乎是正确的:我需要使用 globalThis.WebSocket
而不是 global.WebSocket
。