Serve Webpack bundle from Koa server using koa2-connect

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.

const webpack = require('webpack');
const devMiddleware = require('webpack-dev-middleware');
const config = require('./webpack.config');
const compile = webpack(config);
const expressDevMiddleware = devMiddleware(compile, {});
app.use(expressDevMiddleware);

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.

const koa2Connect = require('koa2-connect');
app.use(koa2Connect(expressDevMiddleware));

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.

const Koa = require('koa');
const app = new Koa();
const webpack = require('webpack');
const devMiddleware = require('webpack-dev-middleware');
const hotMiddleware = require('webpack-hot-middleware');
const config = require('./webpack.config');
const koa2Connect = require('koa2-connect');

const compile = webpack(config);
const expressDevMiddleware = devMiddleware(compile, {});
const expressHotMiddleware = hotMiddleware(compile);
// convert to koaMiddleware!
app.use(koa2Connect(expressDevMiddleware));
app.use(koa2Connect(expressHotMiddleware));

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

Related Posts

One thought on “Serve Webpack bundle from Koa server using koa2-connect

  1. I have some issue in a project with same configuration after update the some package it doesnot work and hot reload is not working.

Leave a Reply

Your email address will not be published.