Koa Webpack Dev Middleware
This package provides a middleware to integrate `webpack-dev-middleware` within Koa 2.x applications, enabling the serving of webpack-bundled assets directly from memory during development. This avoids disk writes and speeds up the development cycle, often paired with `webpack-hot-middleware` for Hot Module Replacement. The current stable version, 2.0.2, appears to be designed for the Koa 2.x ecosystem and Node.js versions 7.6.0 and above. Its release cadence seems to be inactive, with no recent updates catering to newer Koa versions (e.g., Koa 3+) or the latest webpack iterations. As a result, it is primarily relevant for maintaining legacy Koa 2.x projects. Key differentiators include its direct API compatibility with Koa's middleware signature, abstracting the underlying `webpack-dev-middleware` for Koa users.
Common errors
-
TypeError: app.use is not a function
cause Using Koa 1.x (which uses generator functions) instead of Koa 2.x (which uses async/await functions).fixUpdate your Koa application to Koa 2.x syntax or use a Koa 1.x compatible webpack dev middleware. For Koa 2.x, ensure `app = new Koa()` is used, not `app = require('koa')()` without 'new'. -
ReferenceError: require is not defined in ES module scope
cause Attempting to use `require()` in an ES Module (`.mjs` file or project with `"type": "module"` in package.json) where `koa-webpack-dev-middleware` is a CommonJS module.fixFor CommonJS modules in an ESM context, use `import { createRequire } from 'module'; const require = createRequire(import.meta.url); const webpackMiddleware = require('koa-webpack-dev-middleware');` or switch your Koa application entry point back to CommonJS. -
Error: Cannot find module 'webpack'
cause The `webpack` package is a peer dependency but is not installed in the project.fixInstall webpack using `npm install webpack` or `yarn add webpack`. -
Files are not served or 404 errors for assets
cause The `publicPath` option in `koa-webpack-dev-middleware` does not match the `output.publicPath` in your webpack configuration, or the server is not correctly routing requests.fixEnsure that `publicPath` in both the webpack configuration and the `koa-webpack-dev-middleware` options are identical (e.g., `/assets/`). Also, verify that your Koa routes are not intercepting requests intended for the middleware.
Warnings
- breaking This package is explicitly built for Koa 2.x. It may not be compatible with Koa 1.x (due to generator middleware) or Koa 3+ (due to potential API changes or CJS/ESM shifts).
- gotcha The package primarily uses CommonJS (`require`). Using it directly in an ESM-only Koa project (`"type": "module"` in package.json) might lead to 'require is not defined' errors or require careful interoperability configuration.
- gotcha This package has not been actively maintained for several years. It may not fully support the latest features or configurations of `webpack` (e.g., webpack 5+) or modern Node.js environments.
Install
-
npm install koa-webpack-dev-middleware -
yarn add koa-webpack-dev-middleware -
pnpm add koa-webpack-dev-middleware
Imports
- webpackMiddleware
const webpackMiddleware = require('koa-webpack-dev-middleware'); - webpackMiddleware
import { webpackMiddleware } from 'koa-webpack-dev-middleware';import webpackMiddleware from 'koa-webpack-dev-middleware';
- webpack
import webpack from 'webpack';
const webpack = require('webpack');
Quickstart
const Koa = require('koa');
const webpack = require('webpack');
const webpackMiddleware = require('koa-webpack-dev-middleware');
const app = new Koa();
const webpackConfig = {
mode: 'development',
entry: './src/index.js',
output: {
path: '/', // Required for webpack-dev-middleware, no real path needed
publicPath: '/assets/'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: { presets: ['@babel/preset-env'] }
}
}
]
}
};
const compiler = webpack(webpackConfig);
app.use(webpackMiddleware(compiler, {
noInfo: false,
quiet: false,
lazy: false,
watchDelay: 300,
publicPath: '/assets/', // Must match webpackConfig.output.publicPath
headers: { 'X-Custom-Header': 'yes' },
stats: { colors: true }
}));
// Add a simple route to verify the server is running
app.use(async ctx => {
if (ctx.path === '/') {
ctx.body = '<html><body><h1>Koa Webpack Dev Middleware Example</h1><script src="/assets/main.js"></script></body></html>';
}
});
app.listen(3000, () => {
console.log('Koa server with webpack dev middleware listening on port 3000');
console.log('Access: http://localhost:3000');
});
// Create a dummy src/index.js if it doesn't exist
// In a real project, this would be your main entry point.
// For demonstration purposes, we ensure the file exists.
const fs = require('fs');
const path = require('path');
const entryPath = path.resolve(__dirname, 'src/index.js');
if (!fs.existsSync(path.dirname(entryPath))) {
fs.mkdirSync(path.dirname(entryPath), { recursive: true });
}
if (!fs.existsSync(entryPath)) {
fs.writeFileSync(entryPath, 'console.log("Hello from webpack-bundled client code!");');
}