2

I'm trying to get HMR to work on the server-side with an express app and I'm seeing some odd behavior. My simple test project;

index.ts

let httpListener: Server = null;

let AppServer = require('./AppServer').default;
const port = Config.serverPort;

if (process.env.NODE_ENV === 'dev') {
    if ((module as any).hot) {
        (module as any).hot.addDisposeHandler((data: any) => {
            httpListener.close();
            AppServer = require('./AppServer').default;
        });
        console.log('index.ts', (module as any).hot.dependencies);
        (module as any).hot.accept((err: any) => {
            console.log('HMR Error', err);
        });
    }
}

httpListener = AppServer.app.listen(port, (error: Error) => {
    if (error) {
        console.error(error);
    } else {
        console.info(`Listening on port ${port}.`);
    }
});

AppServer.ts

class AppServer {
    public app: express.Application = express();

    constructor() {    
        this.app.use('/api', (new ApiRouter()).router);
    }
}

export default new AppServer();

and ApiRouter.ts

export class ApiRouter {
    public router: express.Router = express.Router();

    constructor() {
        this.router.use('/auth', (new AuthRouter()).router);

        this.router.get('/', (req, res) => {
            res.json({success: true});
        });
    }
}

Webpack bundles correctly, and HMR reports modules being updated. If I change some code in index.ts, those changes take effect. However, when I flip {success: true} to {success: false}, I see HMR update;

[HMR] Updated modules:
[HMR]  - ./src/server/AppServer.ts
[HMR]  - ./src/server/index.ts
[HMR]  - ./src/server/api/ApiRouter.ts

but when I hit the endpoint, I get back {success: true}. So despite HMR seemingly doing the right thing, the code isn't being changed at run-time. I suspect I'm missing something fundamental about how module.hot.accept works here, but I can not figure out where I'm going wrong.

Has anyone gotten this to work correctly?

XeroxDucati
  • 5,130
  • 2
  • 37
  • 66

0 Answers0