Skip to content

Commit 01bf44f

Browse files
committed
feat: run webpack-dev-server as a compiler plugin
1 parent 66ef3ef commit 01bf44f

16 files changed

Lines changed: 353 additions & 38 deletions

‎.changeset/dev-server-6-plugin.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack-cli": minor
3+
---
4+
5+
feat: run `webpack-dev-server@6` as a compiler plugin. The CLI drives watch compilation, prints build stats and closes the compiler on shutdown. Older dev servers continue to manage their own compilation.

‎.prettierignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ test/build/config/error-commonjs/syntax-error.js
1111
test/build/config/error-array/webpack.config.js
1212
test/build/config/error-mjs/syntax-error.mjs
1313
test/configtest/with-config-path/syntax-error.config.js
14+
test/serve/error-handling/src/syntax-error.js
1415
test/build/build-errors/stats.json
1516

1617
/.nx/workspace-data

‎eslint.config.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ export default defineConfig([
1717
"test/configtest/with-config-path/syntax-error.config.js",
1818
"test/build/config-format/auto/webpack.config.js",
1919
"test/build/config-format/typescript-tsx/webpack.config.jsx",
20+
"test/serve/error-handling/src/syntax-error.js",
2021
]),
2122
{
2223
extends: [config],

‎packages/webpack-cli/src/webpack-cli.ts‎

Lines changed: 110 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -2221,10 +2221,12 @@ class WebpackCLI {
22212221
return;
22222222
}
22232223

2224-
const DevServer: DevServerConstructor = cmd.context.devServer;
2224+
const DevServer: DevServerConstructor = devServer;
2225+
const isDevServerPlugin =
2226+
typeof (DevServer.prototype as { apply?: unknown }).apply === "function";
22252227
const servers: InstanceType<DevServerConstructor>[] = [];
22262228

2227-
if (this.#needWatchStdin(compiler)) {
2229+
if (!isDevServerPlugin && this.#needWatchStdin(compiler)) {
22282230
process.stdin.on("end", () => {
22292231
Promise.all(servers.map((server) => server.stop())).then(() => {
22302232
process.exit(0);
@@ -2240,6 +2242,7 @@ class WebpackCLI {
22402242
const usedPorts: number[] = [];
22412243
// @ts-expect-error different versions of the `Schema` type
22422244
const devServerArgs = this.#getArguments(webpack, devServer.schema);
2245+
let appliedDevServers = 0;
22432246

22442247
for (const compilerForDevServer of compilersForDevServer) {
22452248
if (compilerForDevServer.options.devServer === false) {
@@ -2283,11 +2286,23 @@ class WebpackCLI {
22832286
}
22842287

22852288
try {
2286-
const server = new DevServer(devServerConfiguration, compiler);
2289+
if (isDevServerPlugin) {
2290+
// v5 typings lack the plugin constructor.
2291+
const DevServerPlugin = DevServer as unknown as new (
2292+
options: DevServerConfiguration,
2293+
) => { apply(compiler: Compiler | MultiCompiler): void };
2294+
2295+
// Serve all child compilers, regardless of which defines devServer.
2296+
new DevServerPlugin(devServerConfiguration).apply(compiler);
2297+
} else {
2298+
const server = new DevServer(devServerConfiguration, compiler);
22872299

2288-
await server.start();
2300+
await server.start();
2301+
2302+
servers.push(server as unknown as InstanceType<DevServerConstructor>);
2303+
}
22892304

2290-
servers.push(server as unknown as InstanceType<DevServerConstructor>);
2305+
appliedDevServers += 1;
22912306
} catch (error) {
22922307
if (this.isValidationError(error as Error)) {
22932308
this.logger.error((error as Error).message);
@@ -2299,10 +2314,69 @@ class WebpackCLI {
22992314
}
23002315
}
23012316

2302-
if (servers.length === 0) {
2317+
if (appliedDevServers === 0) {
23032318
this.logger.error("No dev server configurations to run");
23042319
process.exit(2);
23052320
}
2321+
2322+
// Older servers manage compilation and signals themselves.
2323+
if (!isDevServerPlugin) {
2324+
return;
2325+
}
2326+
2327+
// Closing the compiler stops the server through its shutdown hook.
2328+
this.#setupGracefulShutdown(compiler);
2329+
2330+
if (this.#needWatchStdin(compiler)) {
2331+
process.stdin.on("end", () => {
2332+
compiler.close(() => {
2333+
process.exit(0);
2334+
});
2335+
});
2336+
process.stdin.resume();
2337+
}
2338+
2339+
const watchCallback = (error: Error | null, stats?: Stats | MultiStats): void => {
2340+
if (error) {
2341+
if (this.isValidationError(error)) {
2342+
this.logger.error(error.message);
2343+
} else {
2344+
this.logger.error(error);
2345+
}
2346+
2347+
process.exit(2);
2348+
}
2349+
2350+
if (!stats) {
2351+
return;
2352+
}
2353+
2354+
if (stats.hasErrors() || (options.failOnWarnings && stats.hasWarnings())) {
2355+
process.exitCode = 1;
2356+
}
2357+
2358+
// Plugin mode leaves stats output to the CLI.
2359+
const statsOptions = this.isMultipleCompiler(compiler)
2360+
? {
2361+
children: compiler.compilers.map((compiler) => compiler.options.stats),
2362+
}
2363+
: compiler.options.stats;
2364+
2365+
const printedStats = stats.toString(statsOptions as StatsOptions);
2366+
2367+
if (printedStats) {
2368+
this.logger.raw(printedStats);
2369+
}
2370+
};
2371+
2372+
if (this.isMultipleCompiler(compiler)) {
2373+
compiler.watch(
2374+
compiler.compilers.map((compiler) => compiler.options.watchOptions || {}),
2375+
watchCallback,
2376+
);
2377+
} else {
2378+
compiler.watch(compiler.options.watchOptions || {}, watchCallback);
2379+
}
23062380
},
23072381
},
23082382
help: {
@@ -3697,6 +3771,35 @@ class WebpackCLI {
36973771
return Boolean(compiler.options.watchOptions?.stdin);
36983772
}
36993773

3774+
#setupGracefulShutdown(compiler: Compiler | MultiCompiler): void {
3775+
let needForceShutdown = false;
3776+
3777+
for (const signal of EXIT_SIGNALS) {
3778+
// eslint-disable-next-line @typescript-eslint/no-loop-func
3779+
const listener = () => {
3780+
if (needForceShutdown) {
3781+
process.exit(0);
3782+
}
3783+
3784+
// Keep fast shutdowns silent.
3785+
const timeout = setTimeout(() => {
3786+
this.logger.info(
3787+
"Gracefully shutting down. To force exit, press ^C again. Please wait...",
3788+
);
3789+
}, 2000);
3790+
3791+
needForceShutdown = true;
3792+
3793+
compiler.close(() => {
3794+
clearTimeout(timeout);
3795+
process.exit(0);
3796+
});
3797+
};
3798+
3799+
process.on(signal, listener);
3800+
}
3801+
}
3802+
37003803
async runWebpack(options: Options, isWatchCommand: boolean): Promise<void> {
37013804
let compiler: Compiler | MultiCompiler;
37023805
let stringifyChunked: typeof stringifyChunkedType;
@@ -3794,32 +3897,7 @@ class WebpackCLI {
37943897
);
37953898

37963899
if (needGracefulShutdown(compiler)) {
3797-
let needForceShutdown = false;
3798-
3799-
for (const signal of EXIT_SIGNALS) {
3800-
// eslint-disable-next-line @typescript-eslint/no-loop-func
3801-
const listener = () => {
3802-
if (needForceShutdown) {
3803-
process.exit(0);
3804-
}
3805-
3806-
// Output message after delay to avoid extra logging
3807-
const timeout = setTimeout(() => {
3808-
this.logger.info(
3809-
"Gracefully shutting down. To force exit, press ^C again. Please wait...",
3810-
);
3811-
}, 2000);
3812-
3813-
needForceShutdown = true;
3814-
3815-
compiler.close(() => {
3816-
clearTimeout(timeout);
3817-
process.exit(0);
3818-
});
3819-
};
3820-
3821-
process.on(signal, listener);
3822-
}
3900+
this.#setupGracefulShutdown(compiler);
38233901

38243902
if (this.#needWatchStdin(compiler)) {
38253903
process.stdin.on("end", () => {

‎test/serve/basic/__snapshots__/serve-basic.test.js.snap.devServer6.webpack5‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,7 @@ exports[`basic serve usage should respect the "publicPath" option from configura
6666
`;
6767

6868
exports[`basic serve usage should throw error when same ports in multicompiler: stderr 1`] = `
69-
"<i> [webpack-dev-server] Project is running at:
70-
<i> [webpack-dev-server] Loopback: http://localhost:<port>/, http://[::1]:<port>/
71-
<i> [webpack-dev-server] On Your Network (IPv4): http://x.x.x.x:<port>/
72-
<i> [webpack-dev-server] On Your Network (IPv6): http://[x:x:x:x:x:x:x:x]:<port>/
73-
<i> [webpack-dev-server] Content not from webpack is served from '<cwd>/test/serve/basic/public' directory
74-
[webpack-cli] ✖ Error: Unique ports must be specified for each devServer option in your webpack configuration. Alternatively, run only 1 devServer config using the --config-name flag to specify your desired config.
69+
"[webpack-cli] ✖ Error: Unique ports must be specified for each devServer option in your webpack configuration. Alternatively, run only 1 devServer config using the --config-name flag to specify your desired config.
7570
at stack"
7671
`;
7772

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
module.exports = {
2+
mode: "development",
3+
entry: "./src/index.js",
4+
devServer: {
5+
devMiddleware: { unknownOption: true },
6+
},
7+
};
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
module.exports = {
2+
mode: "development",
3+
entry: "./src/syntax-error.js",
4+
};
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
"use strict";
2+
3+
/* eslint-disable jest/require-top-level-describe -- Version-gated describe */
4+
5+
const [devServerVersion] = require("webpack-dev-server/package.json").version;
6+
const { run, runWatch } = require("../../utils/test-utils");
7+
8+
const getGetPort = () => import("get-port");
9+
10+
// Only plugin mode uses the CLI's watch callback.
11+
const describeDevServer6 = devServerVersion === "5" ? describe.skip : describe;
12+
13+
describeDevServer6("serve error handling", () => {
14+
let port;
15+
16+
beforeEach(async () => {
17+
port = await (await getGetPort()).default();
18+
});
19+
20+
test("should print the stats with errors and keep serving when the compilation fails", async () => {
21+
const { stderr, stdout } = await runWatch(
22+
__dirname,
23+
["serve", "--config", "error.config.js", "--port", port],
24+
{
25+
stdoutKillStr: /ERROR/,
26+
stderrKillStr: /Project is running at:/,
27+
},
28+
);
29+
30+
expect(stdout).toContain("ERROR in");
31+
expect(stderr).toContain("Project is running at:");
32+
});
33+
34+
test("should print the stats with warnings using the '--fail-on-warnings' option", async () => {
35+
const { stderr, stdout } = await runWatch(
36+
__dirname,
37+
["serve", "--config", "warning.config.js", "--fail-on-warnings", "--port", port],
38+
{
39+
stdoutKillStr: /WARNING/,
40+
stderrKillStr: /Project is running at:/,
41+
},
42+
);
43+
44+
expect(stdout).toContain("WARNING");
45+
expect(stderr).toContain("Project is running at:");
46+
});
47+
48+
test("should log the error and exit when the dev server fails inside the watch run", async () => {
49+
const { exitCode, stderr, stdout } = await run(__dirname, [
50+
"serve",
51+
"--config",
52+
"setup-failure.config.js",
53+
]);
54+
55+
expect(exitCode).toBe(2);
56+
expect(stderr).toContain("Injected middleware failure");
57+
expect(stdout).toBeFalsy();
58+
});
59+
60+
test("should log the validation error and exit when a middleware option is invalid", async () => {
61+
const { exitCode, stderr, stdout } = await run(__dirname, [
62+
"serve",
63+
"--config",
64+
"bad-middleware.config.js",
65+
]);
66+
67+
expect(exitCode).toBe(2);
68+
expect(stderr).toContain(
69+
"Dev Middleware has been initialized using an options object that does not match the API schema",
70+
);
71+
expect(stderr).not.toContain("at Server.setupMiddlewares");
72+
expect(stdout).toBeFalsy();
73+
});
74+
});
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
module.exports = {
2+
mode: "development",
3+
entry: "./src/index.js",
4+
devServer: {
5+
setupMiddlewares: () => {
6+
throw new Error("Injected middleware failure");
7+
},
8+
},
9+
};
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
console.log("ok");

0 commit comments

Comments
 (0)