node.jstypescriptexpresschokidar

How do you hot-reload express when tsc recompiles?


I have a simple nodeJS server and I have it set to watch for changes on the code using tsc --watch. What I was wondering is how do I set up express to reload itself when I make changes to the code (note I am asking specifically on Windows)?

I am presuming it is something to do with chokidar in which I have the following index.ts code

import AWS from "aws-sdk";
import express from "express";
import chokidar from "chokidar";

console.log(AWS.S3);

const route = express.Router();

route.get("/signed-url-put-object", async (req, res) => {
  console.log(process.env)
});

if (process.env.NODE_ENV !== "production") {
  const watcher = chokidar.watch("./index.js");
  watcher.on("all", ()=> {
    console.log("reloading...");
    // what do I do here?
  })
  
}
express().listen(3000, ()=>console.log('listening'))

Solution

  • Try this snippet that I took from this repo.

    watcher.on('ready', function() {
      watcher.on('all', function() {
        console.log("Clearing /server/ module cache from server");
        Object.keys(require.cache).forEach(function(id) {
          if (/[\/\\]server[\/\\]/.test(id)) delete require.cache[id];
        });
      });
    });
    

    Keep in mind you might run into some issues.

    I usually use nodemon and concurrently for my hot reloading needs when both front-end and back-end are in the same repo.

    With concurrently and nodemon, I would have something like this.

    "scripts": {
        "start": "concurrently \"yarn start:fe\" \"yarn start:watch\"",
        "start:watch": "nodemon --inspect=5858 ./server/server.ts",
        "start:be": "set TS_NODE_PROJECT=./tsconfig.server.json && node --inspect=5858 -r ts-node/register ./server/server.ts",
        "start:fe": "react-app-rewired start --scripts-version react-scripts",
    }