Express-style development middleware for webpack that serves files from memory and handles compilation in watch mode
—
The main webpack-dev-middleware function creates Express-style middleware that serves webpack bundles from memory during development.
function webpackDevMiddleware<RequestInternal, ResponseInternal>(
compiler: Compiler | MultiCompiler,
options?: Options<RequestInternal, ResponseInternal>
): API<RequestInternal, ResponseInternal>;Parameters:
compiler: Webpack Compiler or MultiCompiler instanceoptions: Optional configuration objectReturns: Middleware function with additional API methods
The returned middleware includes additional methods for advanced control:
getFilenameFromUrl(url: string, extra?: Extra): string | undefined;Converts a URL to the corresponding filename in webpack's output file system.
Parameters:
url: The URL to convertextra: Optional extra context including stats and error informationReturns: The filename or undefined if not found
Example:
const middleware = webpackDevMiddleware(compiler);
const filename = middleware.getFilenameFromUrl("/bundle.js");
// Returns the actual file path in webpack's outputwaitUntilValid(callback?: Callback): void;Waits until webpack compilation is complete before executing the callback.
Parameters:
callback: Optional callback function called when compilation is validExample:
middleware.waitUntilValid((stats) => {
console.log("Webpack compilation is complete");
console.log("Stats:", stats);
});invalidate(callback?: Callback): void;Invalidates the current webpack compilation and triggers recompilation, then waits for completion.
Parameters:
callback: Optional callback function called when recompilation is completeExample:
// Force recompilation
middleware.invalidate((stats) => {
console.log("Recompilation complete");
});close(callback?: (err: Error | null | undefined) => void): void;Closes the middleware and stops webpack watching.
Parameters:
callback: Optional callback function called when close operation completesExample:
// Shutdown the middleware
middleware.close((err) => {
if (err) console.error("Error closing middleware:", err);
else console.log("Middleware closed successfully");
});context: Context<RequestInternal, ResponseInternal>;Provides access to the internal middleware context and state.
interface Context<RequestInternal, ResponseInternal> {
state: boolean;
stats: Stats | MultiStats | undefined;
callbacks: Callback[];
options: Options<RequestInternal, ResponseInternal>;
compiler: Compiler | MultiCompiler;
watching: Watching | MultiWatching | undefined;
logger: Logger;
outputFileSystem: OutputFileSystem;
}Properties:
state: Current compilation state (true when valid)stats: Latest webpack compilation statisticscallbacks: Pending callback functionsoptions: Middleware configuration optionscompiler: The webpack compiler instancewatching: Webpack file watching instancelogger: Webpack infrastructure loggeroutputFileSystem: File system used for webpack outputtype Callback = (stats?: Stats | MultiStats) => void;
type NextFunction = (err?: any) => void;
interface Extra {
stats?: import("fs").Stats;
errorCode?: number;
immutable?: boolean;
}
type Logger = ReturnType<Compiler["getInfrastructureLogger"]>;
type OutputFileSystem = import("webpack").OutputFileSystem & {
createReadStream?: typeof import("fs").createReadStream;
statSync: import("fs").StatSyncFn;
readFileSync: typeof import("fs").readFileSync;
};const express = require("express");
const webpack = require("webpack");
const webpackDevMiddleware = require("webpack-dev-middleware");
const app = express();
const compiler = webpack(webpackConfig);
const middleware = webpackDevMiddleware(compiler, {
publicPath: "/assets/",
stats: "minimal"
});
app.use(middleware);
// Access additional functionality
middleware.waitUntilValid(() => {
console.log("Ready to serve requests");
});const middleware = webpackDevMiddleware(compiler);
app.get("/api/build-info", (req, res) => {
const stats = middleware.context.stats;
const isValid = middleware.context.state;
res.json({
buildComplete: isValid,
compilation: stats ? stats.toJson() : null
});
});const middleware = webpackDevMiddleware(compiler);
// Trigger rebuild when files change outside webpack's watch
app.post("/api/rebuild", (req, res) => {
middleware.invalidate((stats) => {
res.json({ success: true, stats: stats.toJson() });
});
});Install with Tessl CLI
npx tessl i tessl/npm-webpack-dev-middleware