5

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???

joowhi
  • 53
  • 1
  • 1
  • 7

2 Answers2

6

Try isomorphic-ws:

npm i isomorphic-ws -s

or universal-websocket-client:

npm install --save universal-websocket-client
iStar
  • 1,112
  • 12
  • 20
1

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;
makim
  • 3,154
  • 4
  • 30
  • 49