The article explains how to serve a Webpack bundle from a Koa server. Webpack is used for preparing client bundles composed of JavaScript, styles and assets. Koa is a node server, very similar to express. The article shows how to use webpack-dev-middleware in Koa request processing pipeline with the help of koa2-connect package.

The webpack-dev-middleware package provides the client bundle over a server endpoint. The below code illustrates the use of webpack-dev-middleware with an express server.

The above code serves bundle.js whenever there is a request for it. The webpack-dev-middleware package provides an express middleware which can be used along with express pipeline. Since Koa uses a different signature than express, app.use(expressDevMiddleware) won’t work with Koa.

The koa2-connect package is useful to connect an express middleware for use with the Koa processing pipeline. The below code shows an example of connecting webpack-dev-middleware (an express middleware) with the Koa app.

The webpack-dev-middleware serves the bundle. It does not provide hot reloading option by itself. Hot reloading is updating parts of the bundle with code changes without any browser refresh. The webpack-hot-middleware takes care of hot reloading.

The webpack-hot-middleware package is another express middleware. Here again, koa2-connect comes to the rescue. The full Koa code for serving client bundle and providing hot reload is shown below.

The koa2-connect package is very useful for making an express middleware work as a koa middleware.

Serve Webpack bundle from Koa server using koa2-connect
Tagged on: