Trigger websocket server to send to the client on webpack recompile

412 Views Asked by At

I have an express server and I am trying to incorporate a websocket in it. I use webpack and run it in watch mode. I want to send a message on the websockt every time webpack recompiles after changes.

I have tried making the websocket server listen to an event then emit that event on webpack recompile but that didn't work. I couldn't get a handle to the ws to call the send function.

Below is a simplified version of my server code. Any help would be appreciated.

const express = require("express");
const https = require("https");
const webpack = require("webpack");
const { Server: WebSocketServer } = require("ws");

const app = express();

// Create HTTPS server using the certificate
const server = https
  .createServer(
    {
      key,
      cert,
    },
    app
  )
  .listen(443);

// Use external server as per https://www.npmjs.com/package/ws#external-https-server
const wsServer = new WebSocketServer({ server });
wsServer.on("connection", (socket, request) => {
  console.log("Client has connected");
});

// Run webpack --watch
webpack(configuration).watch(
  {
    /* watchOptions */
  },
  (err, stats) => {
    console.log(
      stats.toString({
        chunks: false,
        colors: true,
      })
    );
    logInColour("green", "✅ Server is up and running");
    // TODO: Send a message using the websocket
  }
);

1

There are 1 best solutions below

0
On BEST ANSWER

I was using the wrong terminology which made it difficult to find answers or help from documentation. The functionality I was after was broadcasting.

I managed to achieve what I wanted by adding the following code where my TODO is

wsServer.clients.forEach(client => client.send('Webpack has recompiled'));