From 3ea59f38e91cab879e1a0df237dce72b1b6426da Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Mon, 16 Feb 2026 03:31:15 +0000 Subject: [PATCH 01/20] feat: plugin support --- lib/Server.js | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/lib/Server.js b/lib/Server.js index 093e03ab62..f2cf9394f4 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -311,6 +311,8 @@ const DEFAULT_ALLOWED_PROTOCOLS = /^(file|.+-extension):/i; * @property {typeof useFn} use */ +const pluginName = "webpack-dev-server"; + /** * @template {BasicApplication} [A=ExpressApplication] * @template {BasicServer} [S=HTTPServer] @@ -330,7 +332,7 @@ class Server { /** * @type {ReturnType} */ - this.logger = this.compiler.getInfrastructureLogger("webpack-dev-server"); + this.logger = this.compiler.getInfrastructureLogger(pluginName); this.options = options; /** * @type {FSWatcher[]} @@ -3429,6 +3431,23 @@ class Server { .then(() => callback(), callback) .catch(callback); } + + /** + * @param {Compiler} compiler compiler + * @returns {void} + */ + apply(compiler) { + const pluginName = this.constructor.name; + this.compiler = compiler; + + this.compiler.hooks.watchRun.tapPromise(pluginName, async () => { + await this.start(); + }); + + this.compiler.hooks.watchClose.tap(pluginName, async () => { + await this.stop(); + }); + } } module.exports = Server; From cff074ef921bd8f0cce6712fcf7aa0750da3b4d7 Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Sat, 21 Feb 2026 18:12:12 +0000 Subject: [PATCH 02/20] fix: correct errors when a compiler is not passed to the constructor --- lib/Server.js | 26 +++++++++++++++++++------- test/e2e/api.test.js | 34 ++++++++++++++++++++++++++++++++++ test/helpers/compile.js | 12 ++++++++++++ 3 files changed, 65 insertions(+), 7 deletions(-) create mode 100644 test/helpers/compile.js diff --git a/lib/Server.js b/lib/Server.js index f2cf9394f4..47b8b85c3b 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -328,11 +328,14 @@ class Server { baseDataPath: "options", }); - this.compiler = compiler; - /** - * @type {ReturnType} - */ - this.logger = this.compiler.getInfrastructureLogger(pluginName); + if (compiler) { + this.compiler = compiler; + + /** + * @type {ReturnType} + */ + this.logger = this.compiler.getInfrastructureLogger(pluginName); + } this.options = options; /** * @type {FSWatcher[]} @@ -1587,6 +1590,9 @@ class Server { * @returns {void} */ setupProgressPlugin() { + // In the case where there is no compiler and it’s not being used as a plugin. + if (this.compiler === undefined) return; + const { ProgressPlugin } = /** @type {MultiCompiler} */ (this.compiler).compilers @@ -1631,6 +1637,7 @@ class Server { * @returns {Promise} */ async initialize() { + if (this.compiler === undefined) return; this.setupHooks(); await this.setupApp(); @@ -1706,7 +1713,7 @@ class Server { needForceShutdown = true; this.stopCallback(() => { - if (typeof this.compiler.close === "function") { + if (typeof this.compiler?.close === "function") { this.compiler.close(() => { // eslint-disable-next-line n/no-process-exit process.exit(); @@ -1781,11 +1788,14 @@ class Server { * @returns {void} */ setupHooks() { + if (this.compiler === undefined) return; + this.compiler.hooks.invalid.tap("webpack-dev-server", () => { if (this.webSocketServer) { this.sendMessage(this.webSocketServer.clients, "invalid"); } }); + this.compiler.hooks.done.tap( "webpack-dev-server", /** @@ -1840,6 +1850,7 @@ class Server { * @returns {void} */ setupMiddlewares() { + if (this.compiler === undefined) return; /** * @type {Array} */ @@ -2331,6 +2342,7 @@ class Server { // middleware for serving webpack bundle /** @type {import("webpack-dev-middleware").API} */ this.middleware = webpackDevMiddleware( + // @ts-expect-error this.compiler, this.options.devMiddleware, ); @@ -3437,8 +3449,8 @@ class Server { * @returns {void} */ apply(compiler) { - const pluginName = this.constructor.name; this.compiler = compiler; + this.logger = this.compiler.getInfrastructureLogger(pluginName); this.compiler.hooks.watchRun.tapPromise(pluginName, async () => { await this.start(); diff --git a/test/e2e/api.test.js b/test/e2e/api.test.js index ee09842d04..4f66eb67be 100644 --- a/test/e2e/api.test.js +++ b/test/e2e/api.test.js @@ -4,11 +4,45 @@ const path = require("node:path"); const webpack = require("webpack"); const Server = require("../../lib/Server"); const config = require("../fixtures/client-config/webpack.config"); +const compile = require("../helpers/compile"); const runBrowser = require("../helpers/run-browser"); const sessionSubscribe = require("../helpers/session-subscribe"); const port = require("../ports-map").api; describe("API", () => { + it("should work with plugin API", async () => { + const compiler = webpack(config); + const server = new Server({ port }); + + server.apply(compiler); + await compile(compiler); + + const { page, browser } = await runBrowser(); + + const pageErrors = []; + const consoleMessages = []; + + page + .on("console", (message) => { + consoleMessages.push(message); + }) + .on("pageerror", (error) => { + pageErrors.push(error); + }); + + await page.goto(`http://127.0.0.1:${port}/`, { + waitUntil: "networkidle0", + }); + + expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( + "console messages", + ); + expect(pageErrors).toMatchSnapshot("page errors"); + + await browser.close(); + compiler.watching.close(); + }); + describe("WEBPACK_SERVE environment variable", () => { const OLD_ENV = process.env; let server; diff --git a/test/helpers/compile.js b/test/helpers/compile.js new file mode 100644 index 0000000000..2696e4b053 --- /dev/null +++ b/test/helpers/compile.js @@ -0,0 +1,12 @@ +"use strict"; + +module.exports = (compiler) => + new Promise((resolve, reject) => { + compiler.run((error, stats) => { + if (error) { + return reject(error); + } + + return resolve(stats); + }); + }); From d7e0cec346324637a7fceebbd278dec9b74946e1 Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Fri, 6 Mar 2026 20:34:57 +0000 Subject: [PATCH 03/20] feat: adapt webpack-dev-middleware.plugin --- lib/Server.js | 1 + types/lib/Server.d.ts | 14 +++++++++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/lib/Server.js b/lib/Server.js index 47b8b85c3b..fba2f1b3d4 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -2345,6 +2345,7 @@ class Server { // @ts-expect-error this.compiler, this.options.devMiddleware, + true, ); } diff --git a/types/lib/Server.d.ts b/types/lib/Server.d.ts index 80a7fbe2df..14a6bce829 100644 --- a/types/lib/Server.d.ts +++ b/types/lib/Server.d.ts @@ -1,8 +1,4 @@ export = Server; -/** - * @typedef {object} BasicApplication - * @property {typeof useFn} use - */ /** * @template {BasicApplication} [A=ExpressApplication] * @template {BasicServer} [S=HTTPServer] @@ -1167,7 +1163,10 @@ declare class Server< * @param {Compiler | MultiCompiler} compiler compiler */ constructor(options: Configuration, compiler: Compiler | MultiCompiler); - compiler: import("webpack").Compiler | import("webpack").MultiCompiler; + compiler: + | import("webpack").Compiler + | import("webpack").MultiCompiler + | undefined; /** * @type {ReturnType} */ @@ -1409,6 +1408,11 @@ declare class Server< * @param {((err?: Error) => void)=} callback callback */ stopCallback(callback?: ((err?: Error) => void) | undefined): void; + /** + * @param {Compiler} compiler compiler + * @returns {void} + */ + apply(compiler: Compiler): void; #private; } declare namespace Server { From f5b39f4ea450197dfcca669d9235c0ef6f3cee37 Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Fri, 6 Mar 2026 22:03:14 -0500 Subject: [PATCH 04/20] feat: enhance plugin API support and update tests for new compile behavior --- .../__snapshots__/api.test.js.snap.webpack5 | 10 +++++ test/e2e/api.test.js | 6 ++- test/helpers/compile.js | 38 +++++++++++++++++-- 3 files changed, 49 insertions(+), 5 deletions(-) diff --git a/test/e2e/__snapshots__/api.test.js.snap.webpack5 b/test/e2e/__snapshots__/api.test.js.snap.webpack5 index 14c74e33ea..7c143f91c9 100644 --- a/test/e2e/__snapshots__/api.test.js.snap.webpack5 +++ b/test/e2e/__snapshots__/api.test.js.snap.webpack5 @@ -165,3 +165,13 @@ exports[`API latest async API should work with callback API: console messages 1` `; exports[`API latest async API should work with callback API: page errors 1`] = `[]`; + +exports[`API should work with plugin API: console messages 1`] = ` +[ + "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", + "[HMR] Waiting for update signal from WDS...", + "Hey.", +] +`; + +exports[`API should work with plugin API: page errors 1`] = `[]`; diff --git a/test/e2e/api.test.js b/test/e2e/api.test.js index 4f66eb67be..aa9dcdd8a2 100644 --- a/test/e2e/api.test.js +++ b/test/e2e/api.test.js @@ -15,7 +15,9 @@ describe("API", () => { const server = new Server({ port }); server.apply(compiler); - await compile(compiler); + + // Use compile helper which waits for the server to be ready + const { watching } = await compile(compiler, port); const { page, browser } = await runBrowser(); @@ -40,7 +42,7 @@ describe("API", () => { expect(pageErrors).toMatchSnapshot("page errors"); await browser.close(); - compiler.watching.close(); + watching.close(); }); describe("WEBPACK_SERVE environment variable", () => { diff --git a/test/helpers/compile.js b/test/helpers/compile.js index 2696e4b053..36f1c480c9 100644 --- a/test/helpers/compile.js +++ b/test/helpers/compile.js @@ -1,12 +1,44 @@ "use strict"; -module.exports = (compiler) => +// Helper function to check if server is ready using fetch +const waitForServer = async (port, timeout = 10000) => { + const start = Date.now(); + + while (Date.now() - start < timeout) { + try { + // eslint-disable-next-line n/no-unsupported-features/node-builtins + await fetch(`http://127.0.0.1:${port}/`); + return; // Server is ready + } catch { + // Server not ready yet, wait and retry + await new Promise((resolve) => { + setTimeout(resolve, 100); + }); + } + } + + throw new Error(`Server on port ${port} not ready after ${timeout}ms`); +}; + +module.exports = (compiler, port = null) => new Promise((resolve, reject) => { - compiler.run((error, stats) => { + const watching = compiler.watch({}, async (error, stats) => { if (error) { + watching.close(); return reject(error); } - return resolve(stats); + // If a port is provided, wait for the server to be ready + if (port) { + try { + await waitForServer(port); + } catch (err) { + watching.close(); + return reject(err); + } + } + + // Return both stats and watching for caller to manage + resolve({ stats, watching }); }); }); From 07c25c9dbe3cb567206bc0d7e92292c0e50c638e Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Mon, 30 Mar 2026 15:00:58 -0500 Subject: [PATCH 05/20] feat: add isPlugin flag to Server class for plugin identification --- lib/Server.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/Server.js b/lib/Server.js index fba2f1b3d4..7b3528e68c 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -362,6 +362,11 @@ class Server { */ this.currentHash = undefined; + /** + * @private + * @type {boolean} + */ + this.isPlugin = false; } static get schema() { @@ -2345,7 +2350,7 @@ class Server { // @ts-expect-error this.compiler, this.options.devMiddleware, - true, + this.isPlugin, ); } @@ -3451,6 +3456,7 @@ class Server { */ apply(compiler) { this.compiler = compiler; + this.isPlugin = true; this.logger = this.compiler.getInfrastructureLogger(pluginName); this.compiler.hooks.watchRun.tapPromise(pluginName, async () => { From 2d6b91f459690d4d3db486d857e7b28770f82716 Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Mon, 30 Mar 2026 15:37:14 -0500 Subject: [PATCH 06/20] feat: prevent multiple server starts on recompilation and ensure clean shutdown --- lib/Server.js | 10 +++++++-- test/e2e/api.test.js | 53 +++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/lib/Server.js b/lib/Server.js index 7b3528e68c..79995d4e1d 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -3459,11 +3459,17 @@ class Server { this.isPlugin = true; this.logger = this.compiler.getInfrastructureLogger(pluginName); + let started = false; + this.compiler.hooks.watchRun.tapPromise(pluginName, async () => { - await this.start(); + if (!started) { + started = true; + await this.start(); + } }); - this.compiler.hooks.watchClose.tap(pluginName, async () => { + this.compiler.hooks.shutdown.tapPromise(pluginName, async () => { + started = false; await this.stop(); }); } diff --git a/test/e2e/api.test.js b/test/e2e/api.test.js index aa9dcdd8a2..56543611d0 100644 --- a/test/e2e/api.test.js +++ b/test/e2e/api.test.js @@ -16,8 +16,7 @@ describe("API", () => { server.apply(compiler); - // Use compile helper which waits for the server to be ready - const { watching } = await compile(compiler, port); + await compile(compiler, port); const { page, browser } = await runBrowser(); @@ -42,7 +41,55 @@ describe("API", () => { expect(pageErrors).toMatchSnapshot("page errors"); await browser.close(); - watching.close(); + await new Promise((resolve) => { + compiler.close(resolve); + }); + }); + + it("should not start the server multiple times on recompilation", async () => { + const compiler = webpack(config); + const server = new Server({ port }); + const startSpy = jest.spyOn(server, "start"); + + server.apply(compiler); + + const { watching } = await compile(compiler, port); + + // Trigger a recompilation by invalidating + await new Promise((resolve) => { + watching.invalidate(() => { + resolve(); + }); + }); + + // Wait for the recompilation to finish + await new Promise((resolve) => { + setTimeout(resolve, 2000); + }); + + expect(startSpy).toHaveBeenCalledTimes(1); + + startSpy.mockRestore(); + await new Promise((resolve) => { + compiler.close(resolve); + }); + }); + + it("should stop the server cleanly via compiler.close()", async () => { + const compiler = webpack(config); + const server = new Server({ port }); + const stopSpy = jest.spyOn(server, "stop"); + + server.apply(compiler); + + await compile(compiler, port); + + await new Promise((resolve) => { + compiler.close(resolve); + }); + + expect(stopSpy).toHaveBeenCalledTimes(1); + stopSpy.mockRestore(); }); describe("WEBPACK_SERVE environment variable", () => { From 72fd93ca69630153e0cf2fc525557f5ca0b8aa30 Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Mon, 30 Mar 2026 15:39:46 -0500 Subject: [PATCH 07/20] fixup! --- types/lib/Server.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/lib/Server.d.ts b/types/lib/Server.d.ts index 14a6bce829..772752db8e 100644 --- a/types/lib/Server.d.ts +++ b/types/lib/Server.d.ts @@ -1195,6 +1195,11 @@ declare class Server< * @type {string | undefined} */ private currentHash; + /** + * @private + * @type {boolean} + */ + private isPlugin; /** * @private * @param {Compiler} compiler compiler From 616b8038b5c95b0e873feab16a93e59bb4bdc0e1 Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Mon, 30 Mar 2026 16:03:20 -0500 Subject: [PATCH 08/20] chore: more tests --- .../logging.test.js.snap.webpack5 | 50 ++++++++ test/e2e/logging.test.js | 121 ++++++++++++++++++ 2 files changed, 171 insertions(+) diff --git a/test/e2e/__snapshots__/logging.test.js.snap.webpack5 b/test/e2e/__snapshots__/logging.test.js.snap.webpack5 index 4c8cc479f7..f9d55c0f6c 100644 --- a/test/e2e/__snapshots__/logging.test.js.snap.webpack5 +++ b/test/e2e/__snapshots__/logging.test.js.snap.webpack5 @@ -1,5 +1,55 @@ // Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing +exports[`logging plugin mode should work and do not log messages about hot and live reloading is enabled 1`] = ` +[ + "[webpack-dev-server] Server started: Hot Module Replacement disabled, Live Reloading disabled, Progress disabled, Overlay enabled.", + "Hey.", +] +`; + +exports[`logging plugin mode should work and log errors by default 1`] = ` +[ + "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", + "[HMR] Waiting for update signal from WDS...", + "Hey.", + "[webpack-dev-server] Errors while compiling. Reload prevented.", + "[webpack-dev-server] ERROR +Error from compilation", +] +`; + +exports[`logging plugin mode should work and log message about live reloading is enabled 1`] = ` +[ + "[webpack-dev-server] Server started: Hot Module Replacement disabled, Live Reloading enabled, Progress disabled, Overlay enabled.", + "Hey.", +] +`; + +exports[`logging plugin mode should work and log messages about hot and live reloading is enabled 1`] = ` +[ + "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", + "[HMR] Waiting for update signal from WDS...", + "Hey.", +] +`; + +exports[`logging plugin mode should work and log warnings by default 1`] = ` +[ + "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", + "[HMR] Waiting for update signal from WDS...", + "Hey.", + "[webpack-dev-server] Warnings while compiling.", + "[webpack-dev-server] WARNING +Warning from compilation", +] +`; + +exports[`logging plugin mode should work when the "client.logging" is "none" 1`] = ` +[ + "Hey.", +] +`; + exports[`logging should work and do not log messages about hot and live reloading is enabled (ws) 1`] = ` [ "[webpack-dev-server] Server started: Hot Module Replacement disabled, Live Reloading disabled, Progress disabled, Overlay enabled.", diff --git a/test/e2e/logging.test.js b/test/e2e/logging.test.js index 9ba530ba3d..aed449463f 100644 --- a/test/e2e/logging.test.js +++ b/test/e2e/logging.test.js @@ -5,6 +5,7 @@ const fs = require("graceful-fs"); const webpack = require("webpack"); const Server = require("../../lib/Server"); const config = require("../fixtures/client-config/webpack.config"); +const compile = require("../helpers/compile"); const HTMLGeneratorPlugin = require("../helpers/html-generator-plugin"); const runBrowser = require("../helpers/run-browser"); const port = require("../ports-map").logging; @@ -241,4 +242,124 @@ describe("logging", () => { }); } } + + describe("plugin mode", () => { + const pluginCases = [ + { + title: + "should work and log messages about hot and live reloading is enabled", + devServerOptions: { + hot: true, + }, + }, + { + title: "should work and log message about live reloading is enabled", + devServerOptions: { + hot: false, + }, + }, + { + title: + "should work and do not log messages about hot and live reloading is enabled", + devServerOptions: { + liveReload: false, + hot: false, + }, + }, + { + title: "should work and log warnings by default", + webpackOptions: { + plugins: [ + { + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "warnings-webpack-plugin", + (compilation) => { + compilation.warnings.push( + new Error("Warning from compilation"), + ); + }, + ); + }, + }, + new HTMLGeneratorPlugin(), + ], + }, + }, + { + title: "should work and log errors by default", + webpackOptions: { + plugins: [ + { + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "warnings-webpack-plugin", + (compilation) => { + compilation.errors.push( + new Error("Error from compilation"), + ); + }, + ); + }, + }, + new HTMLGeneratorPlugin(), + ], + }, + }, + { + title: 'should work when the "client.logging" is "none"', + devServerOptions: { + client: { + logging: "none", + }, + }, + }, + ]; + + for (const testCase of pluginCases) { + it(`${testCase.title}`, async () => { + const compiler = webpack({ ...config, ...testCase.webpackOptions }); + const devServerOptions = { + port, + ...testCase.devServerOptions, + }; + const server = new Server(devServerOptions); + + server.apply(compiler); + + await compile(compiler, port); + + const { page, browser } = await runBrowser(); + + try { + const consoleMessages = []; + + page.on("console", (message) => { + consoleMessages.push(message); + }); + + await page.goto(`http://127.0.0.1:${port}/`, { + waitUntil: "networkidle0", + }); + + expect( + consoleMessages.map((message) => + message + .text() + .replaceAll("\\", "/") + .replaceAll( + new RegExp(process.cwd().replaceAll("\\", "/"), "g"), + "", + ), + ), + ).toMatchSnapshot(); + } finally { + await browser.close(); + await new Promise((resolve) => { + compiler.close(resolve); + }); + } + }); + } + }); }); From c8b6c2cf33f17681b12af66c1f2583bb821dad2a Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Sun, 26 Apr 2026 14:03:04 -0500 Subject: [PATCH 09/20] feat: enhance server setup process --- lib/Server.js | 39 +++++++-- .../__snapshots__/api.test.js.snap.webpack5 | 20 +++++ test/e2e/api.test.js | 85 +++++++++++++++++++ 3 files changed, 138 insertions(+), 6 deletions(-) diff --git a/lib/Server.js b/lib/Server.js index 79995d4e1d..10a9a0952a 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -3257,6 +3257,15 @@ class Server { * @returns {Promise} */ async start() { + await this.setup(); + await this.listen(); + } + + /** + * @private + * @returns {Promise} + */ + async setup() { await this.normalizeOptions(); if (this.options.ipc) { @@ -3308,7 +3317,13 @@ class Server { } await this.initialize(); + } + /** + * @private + * @returns {Promise} + */ + async listen() { const listenOptions = this.options.ipc ? { path: this.options.ipc } : { host: this.options.host, port: this.options.port }; @@ -3459,17 +3474,29 @@ class Server { this.isPlugin = true; this.logger = this.compiler.getInfrastructureLogger(pluginName); - let started = false; + /** @type {Promise | undefined} */ + let setupPromise; + let listening = false; - this.compiler.hooks.watchRun.tapPromise(pluginName, async () => { - if (!started) { - started = true; - await this.start(); + const ensureSetup = () => { + if (!setupPromise) { + setupPromise = this.setup(); } + return setupPromise; + }; + + this.compiler.hooks.beforeCompile.tapPromise(pluginName, ensureSetup); + + this.compiler.hooks.done.tapPromise(pluginName, async () => { + if (listening) return; + listening = true; + await ensureSetup(); + await this.listen(); }); this.compiler.hooks.shutdown.tapPromise(pluginName, async () => { - started = false; + setupPromise = undefined; + listening = false; await this.stop(); }); } diff --git a/test/e2e/__snapshots__/api.test.js.snap.webpack5 b/test/e2e/__snapshots__/api.test.js.snap.webpack5 index 7c143f91c9..a8a8590c52 100644 --- a/test/e2e/__snapshots__/api.test.js.snap.webpack5 +++ b/test/e2e/__snapshots__/api.test.js.snap.webpack5 @@ -166,6 +166,26 @@ exports[`API latest async API should work with callback API: console messages 1` exports[`API latest async API should work with callback API: page errors 1`] = `[]`; +exports[`API plugin in webpack config should work when added to webpack config plugins array: console messages 1`] = ` +[ + "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", + "[HMR] Waiting for update signal from WDS...", + "Hey.", +] +`; + +exports[`API plugin in webpack config should work when added to webpack config plugins array: page errors 1`] = `[]`; + +exports[`API plugin in webpack config should work with output.clean: true: console messages 1`] = ` +[ + "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", + "[HMR] Waiting for update signal from WDS...", + "Hey.", +] +`; + +exports[`API plugin in webpack config should work with output.clean: true: page errors 1`] = `[]`; + exports[`API should work with plugin API: console messages 1`] = ` [ "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", diff --git a/test/e2e/api.test.js b/test/e2e/api.test.js index 56543611d0..c0e3201bb7 100644 --- a/test/e2e/api.test.js +++ b/test/e2e/api.test.js @@ -92,6 +92,91 @@ describe("API", () => { stopSpy.mockRestore(); }); + describe("plugin in webpack config", () => { + it("should work when added to webpack config plugins array", async () => { + const server = new Server({ port }); + const compiler = webpack({ + ...config, + plugins: [...config.plugins, server], + }); + + await compile(compiler, port); + + const { page, browser } = await runBrowser(); + + try { + const pageErrors = []; + const consoleMessages = []; + + page + .on("console", (message) => { + consoleMessages.push(message); + }) + .on("pageerror", (error) => { + pageErrors.push(error); + }); + + await page.goto(`http://127.0.0.1:${port}/`, { + waitUntil: "networkidle0", + }); + + expect( + consoleMessages.map((message) => message.text()), + ).toMatchSnapshot("console messages"); + expect(pageErrors).toMatchSnapshot("page errors"); + } finally { + await browser.close(); + await new Promise((resolve) => { + compiler.close(resolve); + }); + } + }); + + it("should work with output.clean: true", async () => { + const server = new Server({ port }); + const compiler = webpack({ + ...config, + output: { + ...config.output, + clean: true, + }, + plugins: [...config.plugins, server], + }); + + await compile(compiler, port); + + const { page, browser } = await runBrowser(); + + try { + const pageErrors = []; + const consoleMessages = []; + + page + .on("console", (message) => { + consoleMessages.push(message); + }) + .on("pageerror", (error) => { + pageErrors.push(error); + }); + + const response = await page.goto(`http://127.0.0.1:${port}/`, { + waitUntil: "networkidle0", + }); + + expect(response.status()).toBe(200); + expect( + consoleMessages.map((message) => message.text()), + ).toMatchSnapshot("console messages"); + expect(pageErrors).toMatchSnapshot("page errors"); + } finally { + await browser.close(); + await new Promise((resolve) => { + compiler.close(resolve); + }); + } + }); + }); + describe("WEBPACK_SERVE environment variable", () => { const OLD_ENV = process.env; let server; From 0583b3f83f125697cccad837abb6767e5b801bcc Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Sun, 26 Apr 2026 14:15:52 -0500 Subject: [PATCH 10/20] refactor: remove unnecessary compiler checks in setup methods --- lib/Server.js | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/lib/Server.js b/lib/Server.js index 10a9a0952a..917bb49383 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -1595,9 +1595,6 @@ class Server { * @returns {void} */ setupProgressPlugin() { - // In the case where there is no compiler and it’s not being used as a plugin. - if (this.compiler === undefined) return; - const { ProgressPlugin } = /** @type {MultiCompiler} */ (this.compiler).compilers @@ -1634,7 +1631,7 @@ class Server { this.server.emit("progress-update", { percent, msg, pluginName }); } }, - ).apply(this.compiler); + ).apply(/** @type {Compiler | MultiCompiler} */ (this.compiler)); } /** @@ -1642,7 +1639,6 @@ class Server { * @returns {Promise} */ async initialize() { - if (this.compiler === undefined) return; this.setupHooks(); await this.setupApp(); @@ -1793,15 +1789,15 @@ class Server { * @returns {void} */ setupHooks() { - if (this.compiler === undefined) return; + const compiler = /** @type {Compiler | MultiCompiler} */ (this.compiler); - this.compiler.hooks.invalid.tap("webpack-dev-server", () => { + compiler.hooks.invalid.tap("webpack-dev-server", () => { if (this.webSocketServer) { this.sendMessage(this.webSocketServer.clients, "invalid"); } }); - this.compiler.hooks.done.tap( + compiler.hooks.done.tap( "webpack-dev-server", /** * @param {Stats | MultiStats} stats stats @@ -1855,7 +1851,6 @@ class Server { * @returns {void} */ setupMiddlewares() { - if (this.compiler === undefined) return; /** * @type {Array} */ From de2a8d0a9a83dd7d86b1b58e9ca265c8505cefa1 Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Sun, 26 Apr 2026 14:55:15 -0500 Subject: [PATCH 11/20] test: ensure server setup and listen methods are called once on recompilation --- test/e2e/api.test.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/test/e2e/api.test.js b/test/e2e/api.test.js index c0e3201bb7..9056d160cb 100644 --- a/test/e2e/api.test.js +++ b/test/e2e/api.test.js @@ -49,7 +49,8 @@ describe("API", () => { it("should not start the server multiple times on recompilation", async () => { const compiler = webpack(config); const server = new Server({ port }); - const startSpy = jest.spyOn(server, "start"); + const setupSpy = jest.spyOn(server, "setup"); + const listenSpy = jest.spyOn(server, "listen"); server.apply(compiler); @@ -67,9 +68,11 @@ describe("API", () => { setTimeout(resolve, 2000); }); - expect(startSpy).toHaveBeenCalledTimes(1); + expect(setupSpy).toHaveBeenCalledTimes(1); + expect(listenSpy).toHaveBeenCalledTimes(1); - startSpy.mockRestore(); + setupSpy.mockRestore(); + listenSpy.mockRestore(); await new Promise((resolve) => { compiler.close(resolve); }); From 6ea09285a05332fba588680111d93f5ef532ef32 Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Fri, 1 May 2026 13:21:18 -0500 Subject: [PATCH 12/20] test: add API plugin tests and snapshots for webpack config integration --- .../api-plugin.test.js.snap.webpack5 | 31 +++ .../__snapshots__/api.test.js.snap.webpack5 | 30 --- test/e2e/api-plugin.test.js | 180 ++++++++++++++++++ test/e2e/api.test.js | 171 ----------------- test/ports-map.js | 1 + 5 files changed, 212 insertions(+), 201 deletions(-) create mode 100644 test/e2e/__snapshots__/api-plugin.test.js.snap.webpack5 create mode 100644 test/e2e/api-plugin.test.js diff --git a/test/e2e/__snapshots__/api-plugin.test.js.snap.webpack5 b/test/e2e/__snapshots__/api-plugin.test.js.snap.webpack5 new file mode 100644 index 0000000000..59483b0daf --- /dev/null +++ b/test/e2e/__snapshots__/api-plugin.test.js.snap.webpack5 @@ -0,0 +1,31 @@ +// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing + +exports[`API (plugin) plugin in webpack config should work when added to webpack config plugins array: console messages 1`] = ` +[ + "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", + "[HMR] Waiting for update signal from WDS...", + "Hey.", +] +`; + +exports[`API (plugin) plugin in webpack config should work when added to webpack config plugins array: page errors 1`] = `[]`; + +exports[`API (plugin) plugin in webpack config should work with output.clean: true: console messages 1`] = ` +[ + "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", + "[HMR] Waiting for update signal from WDS...", + "Hey.", +] +`; + +exports[`API (plugin) plugin in webpack config should work with output.clean: true: page errors 1`] = `[]`; + +exports[`API (plugin) should work with plugin API: console messages 1`] = ` +[ + "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", + "[HMR] Waiting for update signal from WDS...", + "Hey.", +] +`; + +exports[`API (plugin) should work with plugin API: page errors 1`] = `[]`; diff --git a/test/e2e/__snapshots__/api.test.js.snap.webpack5 b/test/e2e/__snapshots__/api.test.js.snap.webpack5 index a8a8590c52..14c74e33ea 100644 --- a/test/e2e/__snapshots__/api.test.js.snap.webpack5 +++ b/test/e2e/__snapshots__/api.test.js.snap.webpack5 @@ -165,33 +165,3 @@ exports[`API latest async API should work with callback API: console messages 1` `; exports[`API latest async API should work with callback API: page errors 1`] = `[]`; - -exports[`API plugin in webpack config should work when added to webpack config plugins array: console messages 1`] = ` -[ - "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", - "[HMR] Waiting for update signal from WDS...", - "Hey.", -] -`; - -exports[`API plugin in webpack config should work when added to webpack config plugins array: page errors 1`] = `[]`; - -exports[`API plugin in webpack config should work with output.clean: true: console messages 1`] = ` -[ - "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", - "[HMR] Waiting for update signal from WDS...", - "Hey.", -] -`; - -exports[`API plugin in webpack config should work with output.clean: true: page errors 1`] = `[]`; - -exports[`API should work with plugin API: console messages 1`] = ` -[ - "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", - "[HMR] Waiting for update signal from WDS...", - "Hey.", -] -`; - -exports[`API should work with plugin API: page errors 1`] = `[]`; diff --git a/test/e2e/api-plugin.test.js b/test/e2e/api-plugin.test.js new file mode 100644 index 0000000000..049d8e8e69 --- /dev/null +++ b/test/e2e/api-plugin.test.js @@ -0,0 +1,180 @@ +"use strict"; + +const webpack = require("webpack"); +const Server = require("../../lib/Server"); +const config = require("../fixtures/client-config/webpack.config"); +const compile = require("../helpers/compile"); +const runBrowser = require("../helpers/run-browser"); +const port = require("../ports-map")["api-plugin"]; + +describe("API (plugin)", () => { + it("should work with plugin API", async () => { + const compiler = webpack(config); + const server = new Server({ port }); + + server.apply(compiler); + + await compile(compiler, port); + + const { page, browser } = await runBrowser(); + + const pageErrors = []; + const consoleMessages = []; + + page + .on("console", (message) => { + consoleMessages.push(message); + }) + .on("pageerror", (error) => { + pageErrors.push(error); + }); + + await page.goto(`http://127.0.0.1:${port}/`, { + waitUntil: "networkidle0", + }); + + expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( + "console messages", + ); + expect(pageErrors).toMatchSnapshot("page errors"); + + await browser.close(); + await new Promise((resolve) => { + compiler.close(resolve); + }); + }); + + it("should not start the server multiple times on recompilation", async () => { + const compiler = webpack(config); + const server = new Server({ port }); + const setupSpy = jest.spyOn(server, "setup"); + const listenSpy = jest.spyOn(server, "listen"); + + server.apply(compiler); + + const { watching } = await compile(compiler, port); + + // Trigger a recompilation by invalidating + await new Promise((resolve) => { + watching.invalidate(() => { + resolve(); + }); + }); + + // Wait for the recompilation to finish + await new Promise((resolve) => { + setTimeout(resolve, 2000); + }); + + expect(setupSpy).toHaveBeenCalledTimes(1); + expect(listenSpy).toHaveBeenCalledTimes(1); + + setupSpy.mockRestore(); + listenSpy.mockRestore(); + await new Promise((resolve) => { + compiler.close(resolve); + }); + }); + + it("should stop the server cleanly via compiler.close()", async () => { + const compiler = webpack(config); + const server = new Server({ port }); + const stopSpy = jest.spyOn(server, "stop"); + + server.apply(compiler); + + await compile(compiler, port); + + await new Promise((resolve) => { + compiler.close(resolve); + }); + + expect(stopSpy).toHaveBeenCalledTimes(1); + stopSpy.mockRestore(); + }); + + describe("plugin in webpack config", () => { + it("should work when added to webpack config plugins array", async () => { + const server = new Server({ port }); + const compiler = webpack({ + ...config, + plugins: [...config.plugins, server], + }); + + await compile(compiler, port); + + const { page, browser } = await runBrowser(); + + try { + const pageErrors = []; + const consoleMessages = []; + + page + .on("console", (message) => { + consoleMessages.push(message); + }) + .on("pageerror", (error) => { + pageErrors.push(error); + }); + + await page.goto(`http://127.0.0.1:${port}/`, { + waitUntil: "networkidle0", + }); + + expect( + consoleMessages.map((message) => message.text()), + ).toMatchSnapshot("console messages"); + expect(pageErrors).toMatchSnapshot("page errors"); + } finally { + await browser.close(); + await new Promise((resolve) => { + compiler.close(resolve); + }); + } + }); + + it("should work with output.clean: true", async () => { + const server = new Server({ port }); + const compiler = webpack({ + ...config, + output: { + ...config.output, + clean: true, + }, + plugins: [...config.plugins, server], + }); + + await compile(compiler, port); + + const { page, browser } = await runBrowser(); + + try { + const pageErrors = []; + const consoleMessages = []; + + page + .on("console", (message) => { + consoleMessages.push(message); + }) + .on("pageerror", (error) => { + pageErrors.push(error); + }); + + const response = await page.goto(`http://127.0.0.1:${port}/`, { + waitUntil: "networkidle0", + }); + + expect(response.status()).toBe(200); + expect( + consoleMessages.map((message) => message.text()), + ).toMatchSnapshot("console messages"); + expect(pageErrors).toMatchSnapshot("page errors"); + } finally { + await browser.close(); + await new Promise((resolve) => { + compiler.close(resolve); + }); + } + }); + }); +}); diff --git a/test/e2e/api.test.js b/test/e2e/api.test.js index 9056d160cb..ee09842d04 100644 --- a/test/e2e/api.test.js +++ b/test/e2e/api.test.js @@ -4,182 +4,11 @@ const path = require("node:path"); const webpack = require("webpack"); const Server = require("../../lib/Server"); const config = require("../fixtures/client-config/webpack.config"); -const compile = require("../helpers/compile"); const runBrowser = require("../helpers/run-browser"); const sessionSubscribe = require("../helpers/session-subscribe"); const port = require("../ports-map").api; describe("API", () => { - it("should work with plugin API", async () => { - const compiler = webpack(config); - const server = new Server({ port }); - - server.apply(compiler); - - await compile(compiler, port); - - const { page, browser } = await runBrowser(); - - const pageErrors = []; - const consoleMessages = []; - - page - .on("console", (message) => { - consoleMessages.push(message); - }) - .on("pageerror", (error) => { - pageErrors.push(error); - }); - - await page.goto(`http://127.0.0.1:${port}/`, { - waitUntil: "networkidle0", - }); - - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( - "console messages", - ); - expect(pageErrors).toMatchSnapshot("page errors"); - - await browser.close(); - await new Promise((resolve) => { - compiler.close(resolve); - }); - }); - - it("should not start the server multiple times on recompilation", async () => { - const compiler = webpack(config); - const server = new Server({ port }); - const setupSpy = jest.spyOn(server, "setup"); - const listenSpy = jest.spyOn(server, "listen"); - - server.apply(compiler); - - const { watching } = await compile(compiler, port); - - // Trigger a recompilation by invalidating - await new Promise((resolve) => { - watching.invalidate(() => { - resolve(); - }); - }); - - // Wait for the recompilation to finish - await new Promise((resolve) => { - setTimeout(resolve, 2000); - }); - - expect(setupSpy).toHaveBeenCalledTimes(1); - expect(listenSpy).toHaveBeenCalledTimes(1); - - setupSpy.mockRestore(); - listenSpy.mockRestore(); - await new Promise((resolve) => { - compiler.close(resolve); - }); - }); - - it("should stop the server cleanly via compiler.close()", async () => { - const compiler = webpack(config); - const server = new Server({ port }); - const stopSpy = jest.spyOn(server, "stop"); - - server.apply(compiler); - - await compile(compiler, port); - - await new Promise((resolve) => { - compiler.close(resolve); - }); - - expect(stopSpy).toHaveBeenCalledTimes(1); - stopSpy.mockRestore(); - }); - - describe("plugin in webpack config", () => { - it("should work when added to webpack config plugins array", async () => { - const server = new Server({ port }); - const compiler = webpack({ - ...config, - plugins: [...config.plugins, server], - }); - - await compile(compiler, port); - - const { page, browser } = await runBrowser(); - - try { - const pageErrors = []; - const consoleMessages = []; - - page - .on("console", (message) => { - consoleMessages.push(message); - }) - .on("pageerror", (error) => { - pageErrors.push(error); - }); - - await page.goto(`http://127.0.0.1:${port}/`, { - waitUntil: "networkidle0", - }); - - expect( - consoleMessages.map((message) => message.text()), - ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); - } finally { - await browser.close(); - await new Promise((resolve) => { - compiler.close(resolve); - }); - } - }); - - it("should work with output.clean: true", async () => { - const server = new Server({ port }); - const compiler = webpack({ - ...config, - output: { - ...config.output, - clean: true, - }, - plugins: [...config.plugins, server], - }); - - await compile(compiler, port); - - const { page, browser } = await runBrowser(); - - try { - const pageErrors = []; - const consoleMessages = []; - - page - .on("console", (message) => { - consoleMessages.push(message); - }) - .on("pageerror", (error) => { - pageErrors.push(error); - }); - - const response = await page.goto(`http://127.0.0.1:${port}/`, { - waitUntil: "networkidle0", - }); - - expect(response.status()).toBe(200); - expect( - consoleMessages.map((message) => message.text()), - ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); - } finally { - await browser.close(); - await new Promise((resolve) => { - compiler.close(resolve); - }); - } - }); - }); - describe("WEBPACK_SERVE environment variable", () => { const OLD_ENV = process.env; let server; diff --git a/test/ports-map.js b/test/ports-map.js index d898970fdf..01c9a61108 100644 --- a/test/ports-map.js +++ b/test/ports-map.js @@ -80,6 +80,7 @@ const listOfTests = { "options-request-response": 2, app: 1, "cross-origin-request": 2, + "api-plugin": 1, }; let startPort = 8089; From 4829d1d34cbbb2b822c9c158ec65978609ae1ddc Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Fri, 1 May 2026 13:43:30 -0500 Subject: [PATCH 13/20] feat: enhance MultiCompiler support in server setup and add related tests --- lib/Server.js | 37 +++++++-- .../api-plugin.test.js.snap.webpack5 | 10 +++ test/e2e/api-plugin.test.js | 82 +++++++++++++++++++ 3 files changed, 123 insertions(+), 6 deletions(-) diff --git a/lib/Server.js b/lib/Server.js index 917bb49383..1c3a33377d 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -3461,7 +3461,7 @@ class Server { } /** - * @param {Compiler} compiler compiler + * @param {Compiler | MultiCompiler} compiler compiler * @returns {void} */ apply(compiler) { @@ -3472,7 +3472,11 @@ class Server { /** @type {Promise | undefined} */ let setupPromise; let listening = false; + let stopped = false; + /** + * @returns {Promise} promise + */ const ensureSetup = () => { if (!setupPromise) { setupPromise = this.setup(); @@ -3480,20 +3484,41 @@ class Server { return setupPromise; }; - this.compiler.hooks.beforeCompile.tapPromise(pluginName, ensureSetup); + const childCompilers = /** @type {MultiCompiler} */ (compiler) + .compilers || [compiler]; + const seenFirstDone = new WeakSet(); + let firstDoneCount = 0; - this.compiler.hooks.done.tapPromise(pluginName, async () => { + /** + * @param {Compiler} childCompiler child compiler + * @returns {Promise} promise + */ + const onChildDone = async (childCompiler) => { if (listening) return; + if (seenFirstDone.has(childCompiler)) return; + seenFirstDone.add(childCompiler); + firstDoneCount++; + if (firstDoneCount < childCompilers.length) return; listening = true; await ensureSetup(); await this.listen(); - }); + }; - this.compiler.hooks.shutdown.tapPromise(pluginName, async () => { + const onChildShutdown = async () => { + if (stopped) return; + stopped = true; setupPromise = undefined; listening = false; await this.stop(); - }); + }; + + for (const childCompiler of childCompilers) { + childCompiler.hooks.beforeCompile.tapPromise(pluginName, ensureSetup); + childCompiler.hooks.done.tapPromise(pluginName, () => + onChildDone(childCompiler), + ); + childCompiler.hooks.shutdown.tapPromise(pluginName, onChildShutdown); + } } } diff --git a/test/e2e/__snapshots__/api-plugin.test.js.snap.webpack5 b/test/e2e/__snapshots__/api-plugin.test.js.snap.webpack5 index 59483b0daf..bbf2712157 100644 --- a/test/e2e/__snapshots__/api-plugin.test.js.snap.webpack5 +++ b/test/e2e/__snapshots__/api-plugin.test.js.snap.webpack5 @@ -1,5 +1,15 @@ // Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing +exports[`API (plugin) MultiCompiler should work with plugin API: console messages 1`] = ` +[ + "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", + "[HMR] Waiting for update signal from WDS...", + "one", +] +`; + +exports[`API (plugin) MultiCompiler should work with plugin API: page errors 1`] = `[]`; + exports[`API (plugin) plugin in webpack config should work when added to webpack config plugins array: console messages 1`] = ` [ "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.", diff --git a/test/e2e/api-plugin.test.js b/test/e2e/api-plugin.test.js index 049d8e8e69..b9f19679b4 100644 --- a/test/e2e/api-plugin.test.js +++ b/test/e2e/api-plugin.test.js @@ -3,6 +3,7 @@ const webpack = require("webpack"); const Server = require("../../lib/Server"); const config = require("../fixtures/client-config/webpack.config"); +const multiCompilerConfig = require("../fixtures/multi-compiler-two-configurations/webpack.config"); const compile = require("../helpers/compile"); const runBrowser = require("../helpers/run-browser"); const port = require("../ports-map")["api-plugin"]; @@ -177,4 +178,85 @@ describe("API (plugin)", () => { } }); }); + + describe("MultiCompiler", () => { + it("should work with plugin API", async () => { + const compiler = webpack(multiCompilerConfig); + const server = new Server({ port }); + + server.apply(compiler); + + await compile(compiler, port); + + const { page, browser } = await runBrowser(); + + try { + const pageErrors = []; + const consoleMessages = []; + + page + .on("console", (message) => { + consoleMessages.push(message); + }) + .on("pageerror", (error) => { + pageErrors.push(error); + }); + + const response = await page.goto( + `http://127.0.0.1:${port}/one-main.html`, + { + waitUntil: "networkidle0", + }, + ); + + expect(response.status()).toBe(200); + expect( + consoleMessages.map((message) => message.text()), + ).toMatchSnapshot("console messages"); + expect(pageErrors).toMatchSnapshot("page errors"); + } finally { + await browser.close(); + await new Promise((resolve) => { + compiler.close(resolve); + }); + } + }); + + it("should call setup and listen once across all child compilers", async () => { + const compiler = webpack(multiCompilerConfig); + const server = new Server({ port }); + const setupSpy = jest.spyOn(server, "setup"); + const listenSpy = jest.spyOn(server, "listen"); + + server.apply(compiler); + + await compile(compiler, port); + + expect(setupSpy).toHaveBeenCalledTimes(1); + expect(listenSpy).toHaveBeenCalledTimes(1); + + setupSpy.mockRestore(); + listenSpy.mockRestore(); + await new Promise((resolve) => { + compiler.close(resolve); + }); + }); + + it("should stop the server only once when all child compilers shut down", async () => { + const compiler = webpack(multiCompilerConfig); + const server = new Server({ port }); + const stopSpy = jest.spyOn(server, "stop"); + + server.apply(compiler); + + await compile(compiler, port); + + await new Promise((resolve) => { + compiler.close(resolve); + }); + + expect(stopSpy).toHaveBeenCalledTimes(1); + stopSpy.mockRestore(); + }); + }); }); From ebbeb037817cc15713b7e622d2272d48b842d29d Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Fri, 1 May 2026 14:33:01 -0500 Subject: [PATCH 14/20] feat: add support for multiple independent plugin servers and enhance port mapping --- lib/Server.js | 91 +++++++++++++++++++++++++++++++++---- test/e2e/api-plugin.test.js | 73 +++++++++++++++++++++++++++++ test/ports-map.js | 1 + 3 files changed, 156 insertions(+), 9 deletions(-) diff --git a/lib/Server.js b/lib/Server.js index 1c3a33377d..8c5c7905e8 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -313,6 +313,20 @@ const DEFAULT_ALLOWED_PROTOCOLS = /^(file|.+-extension):/i; const pluginName = "webpack-dev-server"; +/** + * Tracks compilers that have an active standalone `Server` attached + * (`new Server(options, compiler).start()`). When a compiler is in this set, + * any `Server` plugin attached to it (or to a `MultiCompiler` that contains + * it) stays passive — otherwise we'd try to bind the same port twice. + * Particularly relevant for `webpack serve`, which creates its own standalone + * server even when the user already added a `Server` instance to `plugins[]`. + * + * Uses a `WeakSet` so a compiler that is no longer referenced anywhere can be + * garbage collected normally, without this module holding it alive. + * @type {WeakSet} + */ +const activeStandaloneCompilers = new WeakSet(); + /** * @template {BasicApplication} [A=ExpressApplication] * @template {BasicServer} [S=HTTPServer] @@ -1340,7 +1354,12 @@ class Server { } if (typeof options.setupExitSignals === "undefined") { - options.setupExitSignals = true; + // In plugin mode, the host (e.g. `webpack-cli`) usually owns process + // signal handling and calls `compiler.close()` on shutdown, which fires + // our `shutdown` hook. Adding our own SIGINT/SIGTERM listeners on top of + // that would race with the host's handler and call `compiler.close()` + // twice. + options.setupExitSignals = !this.isPlugin; } if (typeof options.static === "undefined") { @@ -3252,8 +3271,36 @@ class Server { * @returns {Promise} */ async start() { - await this.setup(); - await this.listen(); + this.#trackStandalone(true); + try { + await this.setup(); + await this.listen(); + } catch (error) { + this.#trackStandalone(false); + throw error; + } + } + + /** + * @param {boolean} active whether to mark or unmark the compiler(s) as + * having an active standalone server + * @returns {void} + */ + #trackStandalone(active) { + if (!this.compiler) return; + const compilers = /** @type {MultiCompiler} */ (this.compiler) + .compilers || [this.compiler]; + if (active) { + activeStandaloneCompilers.add(this.compiler); + for (const child of compilers) { + activeStandaloneCompilers.add(child); + } + } else { + activeStandaloneCompilers.delete(this.compiler); + for (const child of compilers) { + activeStandaloneCompilers.delete(child); + } + } } /** @@ -3370,6 +3417,8 @@ class Server { * @returns {Promise} */ async stop() { + this.#trackStandalone(false); + if (this.bonjour) { await /** @type {Promise} */ ( new Promise((resolve) => { @@ -3474,27 +3523,51 @@ class Server { let listening = false; let stopped = false; + const childCompilers = /** @type {MultiCompiler} */ (compiler) + .compilers || [compiler]; + const seenFirstDone = new WeakSet(); + let firstDoneCount = 0; + + // Returns true when a standalone `Server` is already attached to our + // compiler (or any of its children). This matters for `webpack serve`: + // it creates its own standalone server even if the user added a `Server` + // instance to `plugins[]`. In that case the plugin must stay passive — + // otherwise we'd try to bind the same port twice. Independent + // server/compiler pairs in the same process are unaffected because they + // don't share any compiler instance. + const isStandaloneRunning = () => { + if (activeStandaloneCompilers.has(compiler)) return true; + for (const child of childCompilers) { + if (activeStandaloneCompilers.has(child)) return true; + } + return false; + }; + + // A one-shot `compiler.run()` (plain `webpack` build) is detected when no + // child compiler is in watch mode. In that case we skip both `setup()` and + // `listen()` so the build can finish and the process can exit normally — + // the user is not in control of the plugin lifecycle here, so we stay + // silent rather than logging a warning. + const isBuildMode = () => + childCompilers.every((child) => !child.watching && !child.options.watch); + /** * @returns {Promise} promise */ const ensureSetup = () => { + if (isStandaloneRunning() || isBuildMode()) return Promise.resolve(); if (!setupPromise) { setupPromise = this.setup(); } return setupPromise; }; - const childCompilers = /** @type {MultiCompiler} */ (compiler) - .compilers || [compiler]; - const seenFirstDone = new WeakSet(); - let firstDoneCount = 0; - /** * @param {Compiler} childCompiler child compiler * @returns {Promise} promise */ const onChildDone = async (childCompiler) => { - if (listening) return; + if (listening || isStandaloneRunning() || isBuildMode()) return; if (seenFirstDone.has(childCompiler)) return; seenFirstDone.add(childCompiler); firstDoneCount++; diff --git a/test/e2e/api-plugin.test.js b/test/e2e/api-plugin.test.js index b9f19679b4..ccdd90cfd1 100644 --- a/test/e2e/api-plugin.test.js +++ b/test/e2e/api-plugin.test.js @@ -7,6 +7,7 @@ const multiCompilerConfig = require("../fixtures/multi-compiler-two-configuratio const compile = require("../helpers/compile"); const runBrowser = require("../helpers/run-browser"); const port = require("../ports-map")["api-plugin"]; +const [portA, portB] = require("../ports-map")["api-plugin-multi"]; describe("API (plugin)", () => { it("should work with plugin API", async () => { @@ -258,5 +259,77 @@ describe("API (plugin)", () => { expect(stopSpy).toHaveBeenCalledTimes(1); stopSpy.mockRestore(); }); + + it("should run two independent plugin servers on different child compilers", async () => { + const serverA = new Server({ port: portA }); + const serverB = new Server({ port: portB }); + const [configA, configB] = multiCompilerConfig; + const compiler = webpack([ + { ...configA, plugins: [...configA.plugins, serverA] }, + { ...configB, plugins: [...configB.plugins, serverB] }, + ]); + + await compile(compiler, portA); + // The second server is independent, but `compile()` only awaits one + // port, so poll the second one until it answers. + await new Promise((resolve) => { + const interval = setInterval(async () => { + try { + await fetch(`http://127.0.0.1:${portB}/`); + clearInterval(interval); + resolve(); + } catch { + // Server not ready yet; keep polling. + } + }, 100); + }); + + const { page, browser } = await runBrowser(); + + try { + const responseA = await page.goto( + `http://127.0.0.1:${portA}/one-main.html`, + { waitUntil: "networkidle0" }, + ); + expect(responseA.status()).toBe(200); + + const responseB = await page.goto( + `http://127.0.0.1:${portB}/two-main.html`, + { waitUntil: "networkidle0" }, + ); + expect(responseB.status()).toBe(200); + } finally { + await browser.close(); + await new Promise((resolve) => { + compiler.close(resolve); + }); + } + }); + + it("should stay passive when a standalone server runs on the same compiler", async () => { + const compiler = webpack(config); + const pluginServer = new Server({ port }); + const standaloneServer = new Server({ port }, compiler); + + const pluginSetupSpy = jest.spyOn(pluginServer, "setup"); + const pluginListenSpy = jest.spyOn(pluginServer, "listen"); + + pluginServer.apply(compiler); + await standaloneServer.start(); + + try { + // The standalone server drives compilation through its own + // webpack-dev-middleware. The plugin's hooks fire during that + // compilation but must stay passive — so the plugin's own setup() and + // listen() are never called. + expect(pluginSetupSpy).not.toHaveBeenCalled(); + expect(pluginListenSpy).not.toHaveBeenCalled(); + } finally { + pluginSetupSpy.mockRestore(); + pluginListenSpy.mockRestore(); + await standaloneServer.stop(); + await pluginServer.stop(); + } + }); }); }); diff --git a/test/ports-map.js b/test/ports-map.js index 01c9a61108..9bd885a471 100644 --- a/test/ports-map.js +++ b/test/ports-map.js @@ -81,6 +81,7 @@ const listOfTests = { app: 1, "cross-origin-request": 2, "api-plugin": 1, + "api-plugin-multi": 2, }; let startPort = 8089; From fd726680e0255c4446e694dd068243ad620323df Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Fri, 1 May 2026 14:44:06 -0500 Subject: [PATCH 15/20] test: add test for passive behavior in build mode with compiler.run --- test/e2e/api-plugin.test.js | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/test/e2e/api-plugin.test.js b/test/e2e/api-plugin.test.js index ccdd90cfd1..b959404a3c 100644 --- a/test/e2e/api-plugin.test.js +++ b/test/e2e/api-plugin.test.js @@ -1,5 +1,7 @@ "use strict"; +const os = require("node:os"); +const path = require("node:path"); const webpack = require("webpack"); const Server = require("../../lib/Server"); const config = require("../fixtures/client-config/webpack.config"); @@ -95,6 +97,42 @@ describe("API (plugin)", () => { stopSpy.mockRestore(); }); + it("should stay passive in build mode (compiler.run)", async () => { + // The shared fixture writes output to "/", which would be unwritable + // outside of webpack-dev-middleware's in-memory FS. Use a tmp dir so the + // real `compiler.run()` can flush its assets. + const compiler = webpack({ + ...config, + output: { + ...config.output, + path: path.join(os.tmpdir(), `wds-build-mode-${Date.now()}`), + }, + }); + const server = new Server({ port }); + const setupSpy = jest.spyOn(server, "setup"); + const listenSpy = jest.spyOn(server, "listen"); + + server.apply(compiler); + + // `compiler.run()` is a one-shot build (no watch). The plugin must stay + // passive so the build can finish and the process can exit normally. + await new Promise((resolve, reject) => { + compiler.run((error) => { + if (error) reject(error); + else resolve(); + }); + }); + + expect(setupSpy).not.toHaveBeenCalled(); + expect(listenSpy).not.toHaveBeenCalled(); + + setupSpy.mockRestore(); + listenSpy.mockRestore(); + await new Promise((resolve) => { + compiler.close(resolve); + }); + }); + describe("plugin in webpack config", () => { it("should work when added to webpack config plugins array", async () => { const server = new Server({ port }); From b3048634994e3146426f30ce167edae45a62715d Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Fri, 1 May 2026 14:46:20 -0500 Subject: [PATCH 16/20] fixup! --- types/lib/Server.d.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/types/lib/Server.d.ts b/types/lib/Server.d.ts index 772752db8e..409c30e420 100644 --- a/types/lib/Server.d.ts +++ b/types/lib/Server.d.ts @@ -1401,6 +1401,16 @@ declare class Server< * @returns {Promise} */ start(): Promise; + /** + * @private + * @returns {Promise} + */ + private setup; + /** + * @private + * @returns {Promise} + */ + private listen; /** * @param {((err?: Error) => void)=} callback callback */ @@ -1414,10 +1424,10 @@ declare class Server< */ stopCallback(callback?: ((err?: Error) => void) | undefined): void; /** - * @param {Compiler} compiler compiler + * @param {Compiler | MultiCompiler} compiler compiler * @returns {void} */ - apply(compiler: Compiler): void; + apply(compiler: Compiler | MultiCompiler): void; #private; } declare namespace Server { From 2caad574988d556dc66f3ffae091c43c986d1aa3 Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Fri, 1 May 2026 15:18:59 -0500 Subject: [PATCH 17/20] feat: add example for using webpack-dev-server as a plugin with configuration --- examples/api/plugin/README.md | 47 +++++++++++++++++++++++++++ examples/api/plugin/app.js | 6 ++++ examples/api/plugin/webpack.config.js | 27 +++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 examples/api/plugin/README.md create mode 100644 examples/api/plugin/app.js create mode 100644 examples/api/plugin/webpack.config.js diff --git a/examples/api/plugin/README.md b/examples/api/plugin/README.md new file mode 100644 index 0000000000..ef79106f4b --- /dev/null +++ b/examples/api/plugin/README.md @@ -0,0 +1,47 @@ +# API: Plugin + +Use `webpack-dev-server` as a webpack plugin by adding an instance to +`plugins[]`. The dev server starts when the first compilation finishes and +stops when the compiler closes — no separate `server.start()` call is needed. + +```js +// webpack.config.js +const WebpackDevServer = require("webpack-dev-server"); + +module.exports = { + // ... + plugins: [new WebpackDevServer({ port: 8080, open: true })], +}; +``` + +If you have existing `devServer` options in your config, spread them into the +plugin instance — the plugin reads its options from its constructor argument, +not from `config.devServer`: + +```js +const devServerOptions = { ...config.devServer, open: true }; +config.plugins.push(new WebpackDevServer(devServerOptions)); +``` + +## Run + +```console +npx webpack --watch +``` + +## What should happen + +1. Open `http://localhost:8080/` in your preferred browser. +2. You should see the text on the page itself change to read `Success!`. +3. Press `Ctrl+C` in the terminal — `webpack-cli` closes the compiler, which + fires the plugin's `shutdown` hook, stopping the dev server cleanly. + +## Notes + +- Use `webpack --watch`, not `webpack serve`. `webpack serve` creates its own + standalone dev server; if you also have a plugin instance in `plugins[]`, + the plugin detects the standalone server and stays passive to avoid binding + the same port twice. +- A plain `webpack` build (no watch) will not start the server — the plugin + detects build mode and stays passive so the build can finish and the process + can exit normally. diff --git a/examples/api/plugin/app.js b/examples/api/plugin/app.js new file mode 100644 index 0000000000..51cf4a396b --- /dev/null +++ b/examples/api/plugin/app.js @@ -0,0 +1,6 @@ +"use strict"; + +const target = document.querySelector("#target"); + +target.classList.add("pass"); +target.innerHTML = "Success!"; diff --git a/examples/api/plugin/webpack.config.js b/examples/api/plugin/webpack.config.js new file mode 100644 index 0000000000..b31e67e125 --- /dev/null +++ b/examples/api/plugin/webpack.config.js @@ -0,0 +1,27 @@ +"use strict"; + +const WebpackDevServer = require("../../../lib/Server"); +// our setup function adds behind-the-scenes bits to the config that all of our +// examples need +const { setup } = require("../../util"); + +const config = setup({ + context: __dirname, + entry: "./app.js", + output: { + filename: "bundle.js", + }, + stats: { + colors: true, + }, +}); + +// `setup()` populates `config.devServer.setupMiddlewares` so that the example +// layout assets (CSS, favicon, icons under `.assets/`) are served by the dev +// server. Forward those options to the plugin instance — without them the +// `` from the shared layout would 404. +config.plugins.push( + new WebpackDevServer({ ...config.devServer, port: 8090, open: true }), +); + +module.exports = config; From 351f88f085bdc453b817939651aba902a12ce2ff Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Fri, 1 May 2026 15:31:21 -0500 Subject: [PATCH 18/20] refactor: update README and remove redundant standalone server handling in Server class --- examples/api/plugin/README.md | 13 ++++--- lib/Server.js | 67 +++-------------------------------- test/e2e/api-plugin.test.js | 26 -------------- 3 files changed, 10 insertions(+), 96 deletions(-) diff --git a/examples/api/plugin/README.md b/examples/api/plugin/README.md index ef79106f4b..019dfaebcd 100644 --- a/examples/api/plugin/README.md +++ b/examples/api/plugin/README.md @@ -38,10 +38,9 @@ npx webpack --watch ## Notes -- Use `webpack --watch`, not `webpack serve`. `webpack serve` creates its own - standalone dev server; if you also have a plugin instance in `plugins[]`, - the plugin detects the standalone server and stays passive to avoid binding - the same port twice. -- A plain `webpack` build (no watch) will not start the server — the plugin - detects build mode and stays passive so the build can finish and the process - can exit normally. +- The plugin works with both `webpack --watch` and `webpack serve`. With + `webpack serve`, `webpack-cli` already creates its own standalone dev server + for the same compiler, so you would end up with two servers running. If + that's intentional (e.g. different ports/hosts), make sure the plugin's + `port` does not clash with the one `webpack-cli` resolves from + `config.devServer` and CLI args. Otherwise prefer one or the other. diff --git a/lib/Server.js b/lib/Server.js index 8c5c7905e8..ea056d4b8f 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -313,20 +313,6 @@ const DEFAULT_ALLOWED_PROTOCOLS = /^(file|.+-extension):/i; const pluginName = "webpack-dev-server"; -/** - * Tracks compilers that have an active standalone `Server` attached - * (`new Server(options, compiler).start()`). When a compiler is in this set, - * any `Server` plugin attached to it (or to a `MultiCompiler` that contains - * it) stays passive — otherwise we'd try to bind the same port twice. - * Particularly relevant for `webpack serve`, which creates its own standalone - * server even when the user already added a `Server` instance to `plugins[]`. - * - * Uses a `WeakSet` so a compiler that is no longer referenced anywhere can be - * garbage collected normally, without this module holding it alive. - * @type {WeakSet} - */ -const activeStandaloneCompilers = new WeakSet(); - /** * @template {BasicApplication} [A=ExpressApplication] * @template {BasicServer} [S=HTTPServer] @@ -3271,36 +3257,8 @@ class Server { * @returns {Promise} */ async start() { - this.#trackStandalone(true); - try { - await this.setup(); - await this.listen(); - } catch (error) { - this.#trackStandalone(false); - throw error; - } - } - - /** - * @param {boolean} active whether to mark or unmark the compiler(s) as - * having an active standalone server - * @returns {void} - */ - #trackStandalone(active) { - if (!this.compiler) return; - const compilers = /** @type {MultiCompiler} */ (this.compiler) - .compilers || [this.compiler]; - if (active) { - activeStandaloneCompilers.add(this.compiler); - for (const child of compilers) { - activeStandaloneCompilers.add(child); - } - } else { - activeStandaloneCompilers.delete(this.compiler); - for (const child of compilers) { - activeStandaloneCompilers.delete(child); - } - } + await this.setup(); + await this.listen(); } /** @@ -3417,8 +3375,6 @@ class Server { * @returns {Promise} */ async stop() { - this.#trackStandalone(false); - if (this.bonjour) { await /** @type {Promise} */ ( new Promise((resolve) => { @@ -3528,21 +3484,6 @@ class Server { const seenFirstDone = new WeakSet(); let firstDoneCount = 0; - // Returns true when a standalone `Server` is already attached to our - // compiler (or any of its children). This matters for `webpack serve`: - // it creates its own standalone server even if the user added a `Server` - // instance to `plugins[]`. In that case the plugin must stay passive — - // otherwise we'd try to bind the same port twice. Independent - // server/compiler pairs in the same process are unaffected because they - // don't share any compiler instance. - const isStandaloneRunning = () => { - if (activeStandaloneCompilers.has(compiler)) return true; - for (const child of childCompilers) { - if (activeStandaloneCompilers.has(child)) return true; - } - return false; - }; - // A one-shot `compiler.run()` (plain `webpack` build) is detected when no // child compiler is in watch mode. In that case we skip both `setup()` and // `listen()` so the build can finish and the process can exit normally — @@ -3555,7 +3496,7 @@ class Server { * @returns {Promise} promise */ const ensureSetup = () => { - if (isStandaloneRunning() || isBuildMode()) return Promise.resolve(); + if (isBuildMode()) return Promise.resolve(); if (!setupPromise) { setupPromise = this.setup(); } @@ -3567,7 +3508,7 @@ class Server { * @returns {Promise} promise */ const onChildDone = async (childCompiler) => { - if (listening || isStandaloneRunning() || isBuildMode()) return; + if (listening || isBuildMode()) return; if (seenFirstDone.has(childCompiler)) return; seenFirstDone.add(childCompiler); firstDoneCount++; diff --git a/test/e2e/api-plugin.test.js b/test/e2e/api-plugin.test.js index b959404a3c..a327c2f4be 100644 --- a/test/e2e/api-plugin.test.js +++ b/test/e2e/api-plugin.test.js @@ -343,31 +343,5 @@ describe("API (plugin)", () => { }); } }); - - it("should stay passive when a standalone server runs on the same compiler", async () => { - const compiler = webpack(config); - const pluginServer = new Server({ port }); - const standaloneServer = new Server({ port }, compiler); - - const pluginSetupSpy = jest.spyOn(pluginServer, "setup"); - const pluginListenSpy = jest.spyOn(pluginServer, "listen"); - - pluginServer.apply(compiler); - await standaloneServer.start(); - - try { - // The standalone server drives compilation through its own - // webpack-dev-middleware. The plugin's hooks fire during that - // compilation but must stay passive — so the plugin's own setup() and - // listen() are never called. - expect(pluginSetupSpy).not.toHaveBeenCalled(); - expect(pluginListenSpy).not.toHaveBeenCalled(); - } finally { - pluginSetupSpy.mockRestore(); - pluginListenSpy.mockRestore(); - await standaloneServer.stop(); - await pluginServer.stop(); - } - }); }); }); From ab97bafb5f3ef4acfc1506b2c3145362848c6b8d Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Fri, 1 May 2026 15:45:30 -0500 Subject: [PATCH 19/20] fixup! --- lib/Server.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/Server.js b/lib/Server.js index ea056d4b8f..5aacb419f7 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -554,14 +554,14 @@ class Server { } if (!dir) { - return path.resolve(cwd, ".cache/webpack-dev-server"); + return path.resolve(cwd, `.cache/${pluginName}`); } else if (process.versions.pnp === "1") { - return path.resolve(dir, ".pnp/.cache/webpack-dev-server"); + return path.resolve(dir, `.pnp/.cache/${pluginName}`); } else if (process.versions.pnp === "3") { - return path.resolve(dir, ".yarn/.cache/webpack-dev-server"); + return path.resolve(dir, `.yarn/.cache/${pluginName}`); } - return path.resolve(dir, "node_modules/.cache/webpack-dev-server"); + return path.resolve(dir, `node_modules/.cache/${pluginName}`); } /** @@ -1241,7 +1241,7 @@ class Server { if (typeof options.ipc === "boolean") { const isWindows = process.platform === "win32"; const pipePrefix = isWindows ? "\\\\.\\pipe\\" : os.tmpdir(); - const pipeName = "webpack-dev-server.sock"; + const pipeName = `${pluginName}.sock`; options.ipc = path.join(pipePrefix, pipeName); } @@ -1796,14 +1796,14 @@ class Server { setupHooks() { const compiler = /** @type {Compiler | MultiCompiler} */ (this.compiler); - compiler.hooks.invalid.tap("webpack-dev-server", () => { + compiler.hooks.invalid.tap(pluginName, () => { if (this.webSocketServer) { this.sendMessage(this.webSocketServer.clients, "invalid"); } }); compiler.hooks.done.tap( - "webpack-dev-server", + pluginName, /** * @param {Stats | MultiStats} stats stats */ From 3e742d1d70639bdd62cc4fe83a9da5a97e60e491 Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Fri, 1 May 2026 16:00:39 -0500 Subject: [PATCH 20/20] test: add more tests --- test/e2e/api-plugin.test.js | 105 ++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) diff --git a/test/e2e/api-plugin.test.js b/test/e2e/api-plugin.test.js index a327c2f4be..db3cfa5bb8 100644 --- a/test/e2e/api-plugin.test.js +++ b/test/e2e/api-plugin.test.js @@ -3,6 +3,7 @@ const os = require("node:os"); const path = require("node:path"); const webpack = require("webpack"); +const WebSocket = require("ws"); const Server = require("../../lib/Server"); const config = require("../fixtures/client-config/webpack.config"); const multiCompilerConfig = require("../fixtures/multi-compiler-two-configurations/webpack.config"); @@ -133,6 +134,110 @@ describe("API (plugin)", () => { }); }); + it("should send 'invalid' to WebSocket clients when recompilation is triggered", async () => { + const compiler = webpack(config); + const server = new Server({ port }); + server.apply(compiler); + + const { watching } = await compile(compiler, port); + + const sawInvalid = await new Promise((resolve, reject) => { + let initialOkSeen = false; + const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`, { + headers: { + host: `127.0.0.1:${port}`, + origin: `http://127.0.0.1:${port}`, + }, + }); + + ws.on("error", reject); + ws.on("message", (raw) => { + const { type } = JSON.parse(raw.toString()); + // Wait for the initial "ok" (sent right after the WS handshake), + // then trigger an invalidation. The server's `compiler.hooks.invalid` + // tap should push an "invalid" message before the next compile + // finishes. + if (!initialOkSeen && type === "ok") { + initialOkSeen = true; + watching.invalidate(); + return; + } + if (type === "invalid") { + ws.close(); + resolve(true); + } + }); + }); + + expect(sawInvalid).toBe(true); + + await new Promise((resolve) => { + compiler.close(resolve); + }); + }); + + it("should use constructor options instead of compiler.options.devServer", async () => { + // Plugin reads its options from its constructor argument; values on + // `compiler.options.devServer` are intentionally ignored. This protects + // the documented contract. + const compiler = webpack({ + ...config, + // Pretend an unrelated `devServer` block exists in the user's config. + // The plugin must not pick `port: portB` from it. + devServer: { port: portB, host: "0.0.0.0" }, + }); + const server = new Server({ port: portA }); + server.apply(compiler); + + await compile(compiler, portA); + + const responseA = await fetch(`http://127.0.0.1:${portA}/`); + expect(responseA.status).toBe(200); + + let portBReachable = true; + try { + await fetch(`http://127.0.0.1:${portB}/`); + } catch { + portBReachable = false; + } + expect(portBReachable).toBe(false); + + await new Promise((resolve) => { + compiler.close(resolve); + }); + }); + + it("should propagate setup errors via the watch callback", async () => { + const compiler = webpack(config); + // Using a URL as `static.directory` throws inside `normalizeOptions` + // during `setup()`. The rejection should bubble out through the + // `beforeCompile.tapPromise` handler and reach `compiler.watch()`'s + // user callback as an error. + const server = new Server({ + port, + static: "https://absolute-url.example/some/path", + }); + server.apply(compiler); + + const error = await new Promise((resolve, reject) => { + compiler.watch({}, (err) => { + if (err) { + resolve(err); + } else { + reject(new Error("expected setup to fail")); + } + }); + }); + + expect(error.message).toMatch( + /Using a URL as static.directory is not supported/, + ); + + await new Promise((resolve) => { + compiler.close(resolve); + }); + }); + describe("plugin in webpack config", () => { it("should work when added to webpack config plugins array", async () => { const server = new Server({ port });