3

Webpack hot reloading (webpack-hot-middleware) works wonderfully for the client; it rebuilds and updates assets on the client whenever a file is changed. But for universal/isomorphic servers, where the server needs to prerender the HTML response, this is very difficult.

The naive solution is to restart (e.g. with nodemon) the server whenever a file is changed, but this closes all client connections, and for large servers, this is very slow.

A slightly better solution is to manually watch assets (e.g. with chokidar), and clear cache/require again once a file is changed. But this requires additional complexity when the dependencies also need to be watched; files must be parsed to determine what they require.

Furthermore, if the codebase is written in a compile-to-js language, it is best to run a compiled server for production (no more babel-node). With a compiled server, it is no longer possible to use the mechanism described above, because:

  • webpack has poor support for dynamic requires: require(variable) as opposed to require('./file.js')
  • node cannot natively require the code

In my case, I've abstracted the require function into a package that uses a babel-registered require (previously I used the babel API, but it relied on a lot of undocumented node source).

This is the solution I currently use in https://github.com/edge/cyc, which works somewhat, but it is haphazard and has plenty of caveats. In general, the more custom code written parallel to webpack, the further one departs from the desired behavior.

Is there a robust way to more easily duplicate webpack's behavior?

Synchronous
  • 101
  • 9

2 Answers2

1

I have written a package which may help a bit. You can use if (module.hot) {...} in your server codes.

In brief, in a webpack config, this function create a server as a forked process. If source files change, webpack re-compile and send a signal to the child process. In your server codes, you can include if (module.hot) {... module.hot.accept(...) ...} to accept or reject the update.

If you accept the update, however, just remember to remove all possible side effects. If rejecting, the server will be restarted again.

I am still learning... hope this helps

Green
  • 4,950
  • 3
  • 27
  • 34
1

I recently put out webpack-hot-server-middleware which is designed to be used alongside webpack-dev-middleware (and optionally webpack-hot-middleware).

It takes a very simple approach allowing you to hot update your server rendering bundle without having to restart the process or do anything particularly special with your code.

Richard Scarrott
  • 6,638
  • 1
  • 35
  • 46