joowhi
joowhi

Reputation: 53

Writing WebSocket client with TypeScript running both on browser and Node.JS

I am writing a typescript code that would run in a web-browser and would be tested with Node.JS.

My client code looks like below.

import * as WebSocket from 'ws';

export class SomeClient {
  constructor(url) {
    this.ws = new WebSocket(url);
  }
  
  send(data: any) {
    this.ws.send(data);
  }
}

I had no problem in writing a unit test code using mocha/chai.

However, trying to bundle this code, browserify includes all the 'ws' node module and the size of the output file is almost 100kb. If I remove the import 'ws' statement, the bundle file size shrinks less than 1kb. But, in this case, the Node.JS test complains with 'WebSocket is not defined' error.

I think, this is because WebSocket is natively supported in web browsers but not supported in Node.JS and the external 'ws' module is required to run properly.

How can I make a bundle with the minimum size for web browsers yet can use in Node.JS???

Upvotes: 5

Views: 14135

Answers (2)

makim
makim

Reputation: 3284

I struggled with the same problem, best solution I could find was to use isomorphic-ws create a decs.d.ts in my typescript rootDir with the following content

declare module "isomorphic-ws";

and then use it inside typescript like that:

import { IsoWebSocket } from "isomorphic-ws";
var ws = new IsoWebSocket("wss://echo.websocket.org") as WebSocket;

Upvotes: 1

iStar
iStar

Reputation: 1120

Try isomorphic-ws:

npm i isomorphic-ws -s

or universal-websocket-client:

npm install --save universal-websocket-client

Upvotes: 6

Related Questions