Skip to content

Commit cd97394

Browse files
committed
fix: preserve exit status and avoid duplicate shutdown in plugin mode
1 parent 01bf44f commit cd97394

6 files changed

Lines changed: 178 additions & 24 deletions

File tree

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

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2293,7 +2293,10 @@ class WebpackCLI {
22932293
) => { apply(compiler: Compiler | MultiCompiler): void };
22942294

22952295
// Serve all child compilers, regardless of which defines devServer.
2296-
new DevServerPlugin(devServerConfiguration).apply(compiler);
2296+
new DevServerPlugin({
2297+
...devServerConfiguration,
2298+
setupExitSignals: false,
2299+
}).apply(compiler);
22972300
} else {
22982301
const server = new DevServer(devServerConfiguration, compiler);
22992302

@@ -2325,12 +2328,12 @@ class WebpackCLI {
23252328
}
23262329

23272330
// Closing the compiler stops the server through its shutdown hook.
2328-
this.#setupGracefulShutdown(compiler);
2331+
this.#setupGracefulShutdown(compiler, true);
23292332

23302333
if (this.#needWatchStdin(compiler)) {
23312334
process.stdin.on("end", () => {
23322335
compiler.close(() => {
2333-
process.exit(0);
2336+
process.exit();
23342337
});
23352338
});
23362339
process.stdin.resume();
@@ -3771,14 +3774,14 @@ class WebpackCLI {
37713774
return Boolean(compiler.options.watchOptions?.stdin);
37723775
}
37733776

3774-
#setupGracefulShutdown(compiler: Compiler | MultiCompiler): void {
3777+
#setupGracefulShutdown(compiler: Compiler | MultiCompiler, preserveExitCode = false): void {
37753778
let needForceShutdown = false;
37763779

37773780
for (const signal of EXIT_SIGNALS) {
37783781
// eslint-disable-next-line @typescript-eslint/no-loop-func
37793782
const listener = () => {
37803783
if (needForceShutdown) {
3781-
process.exit(0);
3784+
process.exit(preserveExitCode ? process.exitCode : 0);
37823785
}
37833786

37843787
// Keep fast shutdowns silent.
@@ -3792,7 +3795,7 @@ class WebpackCLI {
37923795

37933796
compiler.close(() => {
37943797
clearTimeout(timeout);
3795-
process.exit(0);
3798+
process.exit(preserveExitCode ? process.exitCode : 0);
37963799
});
37973800
};
37983801

‎test/serve/error-handling/serve-error-handling.test.js‎

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ describeDevServer6("serve error handling", () => {
1818
});
1919

2020
test("should print the stats with errors and keep serving when the compilation fails", async () => {
21-
const { stderr, stdout } = await runWatch(
21+
const { exitCode, stderr, stdout } = await runWatch(
2222
__dirname,
2323
["serve", "--config", "error.config.js", "--port", port],
2424
{
@@ -29,10 +29,11 @@ describeDevServer6("serve error handling", () => {
2929

3030
expect(stdout).toContain("ERROR in");
3131
expect(stderr).toContain("Project is running at:");
32+
expect(exitCode).toBe(1);
3233
});
3334

3435
test("should print the stats with warnings using the '--fail-on-warnings' option", async () => {
35-
const { stderr, stdout } = await runWatch(
36+
const { exitCode, stderr, stdout } = await runWatch(
3637
__dirname,
3738
["serve", "--config", "warning.config.js", "--fail-on-warnings", "--port", port],
3839
{
@@ -43,8 +44,64 @@ describeDevServer6("serve error handling", () => {
4344

4445
expect(stdout).toContain("WARNING");
4546
expect(stderr).toContain("Project is running at:");
47+
expect(exitCode).toBe(1);
4648
});
4749

50+
test.each(process.platform === "win32" ? ["stdin"] : ["SIGINT", "SIGTERM", "stdin"])(
51+
"should preserve failure status and close the compiler on %s",
52+
async (trigger) => {
53+
const { exitCode, stdout, stderr } = await runWatch(
54+
__dirname,
55+
[
56+
"serve",
57+
"--config",
58+
"shutdown.config.js",
59+
"--fail-on-warnings",
60+
"--watch-options-stdin",
61+
"--port",
62+
port,
63+
],
64+
{
65+
handler: (proc) => {
66+
let output = "";
67+
let serverOutput = "";
68+
let stopping = false;
69+
const stop = () => {
70+
if (
71+
stopping ||
72+
!output.includes("WARNING") ||
73+
!serverOutput.includes("Server ready")
74+
) {
75+
return;
76+
}
77+
78+
stopping = true;
79+
80+
if (trigger === "stdin") {
81+
proc.stdin.end();
82+
} else {
83+
proc.kill(trigger);
84+
}
85+
};
86+
87+
proc.stdout.on("data", (chunk) => {
88+
output += chunk.toString();
89+
stop();
90+
});
91+
proc.stderr.on("data", (chunk) => {
92+
serverOutput += chunk.toString();
93+
stop();
94+
});
95+
},
96+
},
97+
);
98+
99+
expect(exitCode).toBe(1);
100+
expect(stderr).toContain("Server ready: 1 SIGINT, 1 SIGTERM");
101+
expect(stdout.match(/Compiler shutdown/g)).toHaveLength(1);
102+
},
103+
);
104+
48105
test("should log the error and exit when the dev server fails inside the watch run", async () => {
49106
const { exitCode, stderr, stdout } = await run(__dirname, [
50107
"serve",
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const configuration = require("./warning.config");
2+
3+
module.exports = {
4+
...configuration,
5+
devServer: {
6+
setupExitSignals: true,
7+
onListening: () => {
8+
console.error(
9+
`Server ready: ${process.listenerCount("SIGINT")} SIGINT, ${process.listenerCount("SIGTERM")} SIGTERM`,
10+
);
11+
},
12+
},
13+
plugins: [
14+
{
15+
apply(compiler) {
16+
compiler.hooks.shutdown.tap("ShutdownTest", () => {
17+
console.log("Compiler shutdown");
18+
});
19+
},
20+
},
21+
],
22+
};

‎test/serve/rebuild/multi.config.js‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,25 @@
1+
const plugins = [
2+
{
3+
apply(compiler) {
4+
compiler.hooks.watchRun.tap("RebuildTest", () => {
5+
console.log(`Watch ${compiler.name}: ${compiler.watching.watchOptions.aggregateTimeout}`);
6+
});
7+
compiler.hooks.afterDone.tap("RebuildTest", () => {
8+
console.log(`Built ${compiler.name}`);
9+
});
10+
compiler.hooks.shutdown.tap("RebuildTest", () => {
11+
console.log(`Closed ${compiler.name}`);
12+
});
13+
},
14+
},
15+
];
16+
117
module.exports = [
218
{
319
name: "app",
420
mode: "development",
521
entry: "./src/index.js",
22+
plugins,
623
output: { filename: "app.js" },
724
watchOptions: {
825
aggregateTimeout: 10,
@@ -12,10 +29,11 @@ module.exports = [
1229
{
1330
name: "worker",
1431
mode: "development",
15-
entry: "./src/index.js",
32+
entry: "./src/worker.js",
33+
plugins,
1634
output: { filename: "worker.js" },
1735
watchOptions: {
18-
aggregateTimeout: 10,
36+
aggregateTimeout: 30,
1937
},
2038
},
2139
];

‎test/serve/rebuild/serve-rebuild.test.js‎

Lines changed: 67 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ const getGetPort = () => import("get-port");
88

99
const entryPath = resolve(__dirname, "./src/index.js");
1010
const originalEntry = readFileSync(entryPath, "utf8");
11+
const workerPath = resolve(__dirname, "./src/worker.js");
12+
const originalWorker = readFileSync(workerPath, "utf8");
1113

1214
describe("serve recompilation", () => {
1315
let port;
@@ -18,6 +20,7 @@ describe("serve recompilation", () => {
1820

1921
afterEach(() => {
2022
writeFileSync(entryPath, originalEntry);
23+
writeFileSync(workerPath, originalWorker);
2124
});
2225

2326
it("should recompile upon file change and log the stats again", async () => {
@@ -84,18 +87,68 @@ describe("serve recompilation", () => {
8487
expect(updatedBody).toContain("serve rebuild test updated");
8588
});
8689

87-
it("should watch every compiler of a multi compiler with its own watch options", async () => {
88-
const { stderr, stdout } = await runWatch(
89-
__dirname,
90-
["serve", "--config", "multi.config.js", "--port", port],
91-
{
92-
stdoutKillStr: /compiled successfully/,
93-
stderrKillStr: /Project is running at:/,
94-
},
95-
);
96-
97-
expect(stdout).toContain("app:");
98-
expect(stdout).toContain("worker:");
99-
expect(stderr).toContain("Project is running at:");
100-
});
90+
it.each(["app", "worker"])(
91+
"should rebuild and serve changes to the %s compiler",
92+
async (name) => {
93+
let updatedBody;
94+
let requestError;
95+
const { stdout } = await runWatch(
96+
__dirname,
97+
["serve", "--config", "multi.config.js", "--port", port],
98+
{
99+
handler: (proc) => {
100+
let output = "";
101+
let serverOutput = "";
102+
let changed = false;
103+
let fetching = false;
104+
const check = () => {
105+
if (
106+
!changed &&
107+
output.includes("Built app") &&
108+
output.includes("Built worker") &&
109+
serverOutput.includes("Project is running at:")
110+
) {
111+
changed = true;
112+
writeFileSync(
113+
name === "app" ? entryPath : workerPath,
114+
`console.log('updated ${name} bundle');\n`,
115+
);
116+
}
117+
118+
if (!fetching && output.split(`Built ${name}`).length === 3) {
119+
fetching = true;
120+
fetch(`http://127.0.0.1:${port}/${name}.js`)
121+
.then((response) => response.text())
122+
.then((body) => {
123+
updatedBody = body;
124+
})
125+
.catch((error) => {
126+
requestError = error;
127+
})
128+
.finally(() => {
129+
processKill(proc);
130+
});
131+
}
132+
};
133+
134+
proc.stdout.on("data", (chunk) => {
135+
output += chunk.toString();
136+
check();
137+
});
138+
proc.stderr.on("data", (chunk) => {
139+
serverOutput += chunk.toString();
140+
check();
141+
});
142+
},
143+
},
144+
);
145+
146+
expect(requestError).toBeUndefined();
147+
expect(updatedBody).toContain(`updated ${name} bundle`);
148+
expect(stdout).toContain("Watch app: 10");
149+
expect(stdout).toContain("Watch worker: 30");
150+
expect(stdout.match(/Closed app/g)).toHaveLength(1);
151+
expect(stdout.match(/Closed worker/g)).toHaveLength(1);
152+
},
153+
);
101154
});

‎test/serve/rebuild/src/worker.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
console.log("serve worker test");

0 commit comments

Comments
 (0)