The `universal-websocket-client` package provides a unified API for WebSocket communication across both browser and Node.js environments. It achieves this by utilizing the native `WebSocket` API in browsers and integrating with the `ws` package for Node.js, allowing developers to write isomorphic applications with a single WebSocket client interface. Currently at version 1.0.3, the package appears to be in an abandoned state, with its last update occurring approximately seven years ago, indicating no active development or maintenance. Its primary differentiator was simplifying cross-environment WebSocket usage before native ESM and modern bundler configurations became prevalent, specifically by avoiding the inclusion of Node.js-specific WebSocket implementations in browser builds.
npm install universal-websocket-clientVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to establish a WebSocket connection and handle messages using `universal-websocket-client`. Includes a minimal Node.js echo server for local testing and illustrates client usage for both Node.js and browser environments.
For new projects, consider using actively maintained alternatives. For Node.js, the `ws` package is a robust choice. For universal/isomorphic applications, consider modern solutions that offer native ESM support, TypeScript definitions, and active community backing like `@ws-kit/client` or directly managing environment-specific WebSocket implementations.
For browser environments, your code must be bundled with a tool like Webpack or Browserify. For Node.js ESM projects, you'll need to configure your bundler to handle CJS modules or use Node.js's `createRequire` utility for explicit CJS imports.
Manually create a `universal-websocket-client.d.ts` file in your project with basic type declarations, for example, `declare module 'universal-websocket-client' { export = WebSocket; }` and extend the global `WebSocket` interface or provide a custom type definition.For browser usage, ensure your code is bundled with Browserify, Webpack, or a similar tool. For Node.js ESM modules, use `import { createRequire } from 'module'; const require = createRequire(import.meta.url); const WebSocket = require('universal-websocket-client');` or switch the file to CommonJS (`.cjs` extension or `"type": "commonjs"` in `package.json`).Ensure the `ws` package is installed as a direct dependency of your project: `npm install ws`. If the issue persists, verify the version of Node.js as modern Node.js versions may have native WebSocket client support.
Try adjusting your import statement in TypeScript: `import WebSocket = require('universal-websocket-client');`. For JavaScript, ensure your bundler is configured to correctly handle CommonJS interop, potentially using `import * as WebSocket from 'universal-websocket-client';` if the module exports are bundled as a namespace, or check bundler-specific plugins/options for CJS compatibility.