Koa Webpack Development Middleware

raw JSON →
6.0.0 verified Thu Apr 23 auth: no javascript

Koa Webpack is a development and hot module reloading middleware for Koa2 applications. It wraps and composes `webpack-dev-middleware` and `webpack-hot-client` into a single, cohesive middleware module, simplifying the integration of Webpack into a Koa server. Version 6.0.0 is the current stable release, which dropped support for Node.js 8. The package generally follows a maintenance release cadence with occasional minor updates, and major versions are released when significant breaking changes occur in its underlying dependencies (like `webpack-hot-client`) or Node.js compatibility is updated. A key differentiator is its ability to automatically use the `webpack` module and `webpack.config.js` from the project root, reducing boilerplate compared to other Koa Webpack integration solutions.

error TypeError: app.use requires a generator function or middleware function
cause You are attempting to use the Promise returned by `koaWebpack()` directly with `app.use()`, instead of the resolved middleware.
fix
Modify your code to const middleware = await koaWebpack(options); app.use(middleware); ensuring you await the Promise.
error Error: Cannot find module 'webpack'
cause The `webpack` package, which is a peer dependency of `koa-webpack`, is not installed in your project.
fix
Install webpack using your package manager: npm install webpack or yarn add webpack.
error TypeError: Cannot read properties of undefined (reading 'publicPath') (or similar for missing options)
cause You are likely using deprecated option names (`dev` or `hot`) that were renamed in `koa-webpack` v5.0.0.
fix
Update your configuration to use devMiddleware instead of dev and hotClient instead of hot.
breaking Node.js 8.x is no longer supported. Applications running on Node.js 8 will break or function incorrectly.
fix Upgrade your Node.js environment to version 10.0.0 or higher.
breaking The `dev` and `hot` options were renamed to `devMiddleware` and `hotClient` respectively.
fix Rename the `dev` option to `devMiddleware` and the `hot` option to `hotClient` when configuring the middleware.
breaking The `koaWebpack()` function now returns a Promise that resolves to the actual middleware, instead of returning the middleware directly.
fix Ensure you `await` the result of `koaWebpack(options)` or handle the returned Promise with `.then()` before passing it to `app.use()`.
gotcha `koa-webpack` has a peer dependency on `webpack` version `^4.28.0` or higher. Failing to install this will result in runtime errors.
fix Install `webpack` version `^4.28.0` or higher in your project's dependencies using `npm install webpack` or `yarn add webpack`.
gotcha Security vulnerabilities in underlying dependencies were patched in `v5.1.1` and `v5.2.3`.
fix Upgrade to `koa-webpack@5.2.3` or a newer version to include these security fixes.
npm install koa-webpack
yarn add koa-webpack
pnpm add koa-webpack

This example sets up a basic Koa server integrated with `koa-webpack`, demonstrating how to use a custom Webpack compiler and configure options for both `webpack-dev-middleware` and `webpack-hot-client`. It listens on port 3000.

const Koa = require('koa');
const koaWebpack = require('koa-webpack');
const webpack = require('webpack');
const path = require('path');

const app = new Koa();

// A minimal webpack configuration for development
const webpackConfig = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/' // Crucial for webpack-dev-middleware to serve assets
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader' // Requires babel-loader, @babel/core, @babel/preset-env
      }
    ]
  }
};

const compiler = webpack(webpackConfig);

(async () => {
  try {
    const middleware = await koaWebpack({
      compiler: compiler,
      devMiddleware: {
        publicPath: webpackConfig.output.publicPath,
        stats: {
          colors: true,
          chunks: false,
          'errors-only': true
        },
        writeToDisk: true // Example: Write assets to disk
      },
      hotClient: {
        logLevel: 'warn', // Example: Suppress verbose hot-client logs
        port: 8081 // Example: Specify a port for HMR WebSocket
      }
    });

    app.use(middleware);

    app.listen(3000, () => {
      console.log('Koa server with webpack-dev-middleware and HMR listening on port 3000');
      console.log('Open http://localhost:3000 in your browser.');
    });
  } catch (error) {
    console.error('Failed to start koa-webpack middleware:', error);
  }
})();