Skip to content

Commit 57f595d

Browse files
feat(client): format one of webpack's problems, wherever it is read
The overlay took formatted strings only. The middleware formats its own payloads on the server, so its client never needed anything else — but a server that sends webpack's error objects to the browser and formats them there had to write that formatting itself, which is what webpack-dev-server carried a client file for. `showProblems` now takes an error object as it comes, and the formatting is `webpack-dev-middleware/client/problem`: `problemLocation`, `problemBody`, `problemLine` and `formatProblem`, the last splitting a problem into the header and body a console wants. The server's own `formatErrors` builds the same shape, so a build reads the same way whether the middleware formatted it or a server sent the object over. Two things it got wrong fall out of that: * An error webpack names no module for sent a first line holding a single space. The overlay reads the first line as the heading, so it drew one with nothing in it. The message goes alone now. * A module built by loaders reports its whole request as `moduleName` (`babel-loader!./app.js`), which reads as noise where the file is what matters. The file comes first, the request follows it, and `file` is used when webpack sets one — once, not appended to itself. A unit test asserts the two formatters agree on every shape rather than trusting them to. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA
1 parent d54e87d commit 57f595d

10 files changed

Lines changed: 518 additions & 11 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
---
2+
"webpack-dev-middleware": minor
3+
---
4+
5+
The overlay now takes one of webpack's errors or warnings as it comes, not
6+
only a formatted string:
7+
8+
```js
9+
import { showProblems } from "webpack-dev-middleware/client/overlay";
10+
11+
showProblems("errors", stats.errors, "build");
12+
```
13+
14+
The middleware formats its own payloads on the server, so its client never
15+
needed this. A server that sends webpack's error objects to the browser and
16+
formats them there — which is what webpack-dev-server does — had to write that
17+
formatting itself. It is `webpack-dev-middleware/client/problem` now, and
18+
`formatProblem` is there for a console as well as an overlay:
19+
20+
```js
21+
import { formatProblem } from "webpack-dev-middleware/client/problem";
22+
23+
const { header, body } = formatProblem("error", error);
24+
// "ERROR in ./src/app.js 3:0", "Module parse failed: ..."
25+
```
26+
27+
The server's own formatting reads the same way as a result, which fixes two
28+
things it got wrong. An error webpack names no module for sent a first line
29+
holding a single space — and the overlay reads the first line as the heading,
30+
so it drew a heading with nothing in it; it now sends the message alone. And a
31+
module built by loaders reports its whole request (`babel-loader!./app.js`),
32+
which read as noise where the file is what matters; the file comes first now,
33+
with the request after it, and `file` is used when webpack sets one.

‎client-src/overlay.js‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
import ansiHTML from "ansi-html-community";
22

3+
import { problemLine } from "./problem.js";
34
import theme from "./theme.js";
45

6+
// Re-exported so a consumer that shows problems in the console as well as in
7+
// the overlay has one import for both. `./client/problem` is the same thing
8+
// without the overlay, for one that only formats.
9+
export { formatProblem, problemLine } from "./problem.js";
10+
511
// eslint-disable-next-line jsdoc/reject-any-type
612
/** @typedef {any} EXPECTED_ANY */
713

@@ -820,23 +826,30 @@ render = renderProblems;
820826

821827
/**
822828
* @param {"errors" | "warnings"} type problem type
823-
* @param {string[]} lines messages to render
829+
* @param {(string | import("./problem.js").Problem)[]} problems what to
830+
* render: a message, or one of webpack's errors or warnings as
831+
* `stats.toJson()` reports it — a server that sends those to the browser
832+
* rather than formatting them itself has nothing to convert
824833
* @param {string=} source who reports them — each source (e.g. this client,
825834
* the webpack-dev-server client, the runtime error capture) keeps its own
826835
* slot and the overlay renders the union of every slot
827836
*/
828-
export function showProblems(type, lines, source = "") {
837+
export function showProblems(type, problems, source = "") {
829838
// Nothing to report is not something to report. Kept as a slot, it made the
830839
// union non-empty, which put an empty card on the page for the reader to
831840
// dismiss by hand — and, once another source cleared, left the page covered
832841
// by an overlay with no problems in it at all.
833-
if (lines.length === 0) {
842+
if (problems.length === 0) {
834843
clear(source);
835844

836845
return;
837846
}
838847

839-
state.problemsBySource[source] = { type, lines: [...lines] };
848+
const lines = problems.map((problem) =>
849+
typeof problem === "string" ? problem : problemLine(problem),
850+
);
851+
852+
state.problemsBySource[source] = { type, lines };
840853

841854
const union =
842855
/** @type {{ type: "errors" | "warnings", lines: string[] }} */

‎client-src/problem.js‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
// Turning one of webpack's problems into something to read.
2+
//
3+
// The middleware formats a build's errors and warnings on the server, so its
4+
// own payloads carry strings and its client never needs this. A server that
5+
// sends webpack's error objects to the browser instead — which is what
6+
// webpack-dev-server does — needs the same shape built there, and had to
7+
// write it itself. Here it is once.
8+
//
9+
// Compiled to an ES5 baseline like the rest of the browser runtime, so
10+
// nothing here is newer than that.
11+
12+
// eslint-disable-next-line jsdoc/reject-any-type
13+
/** @typedef {any} EXPECTED_ANY */
14+
15+
/**
16+
* One of webpack's errors or warnings, as `stats.toJson()` reports it. Only
17+
* the fields that say something about where and what; anything else on a
18+
* `StatsError` is ignored.
19+
* @typedef {object} Problem
20+
* @property {string=} file the file the problem is in
21+
* @property {string=} moduleName the module's request, loaders and all
22+
* @property {string=} loc line and column within the module
23+
* @property {string=} message what went wrong
24+
* @property {(string[] | EXPECTED_ANY)=} stack frames webpack attached, when it did
25+
*/
26+
27+
/**
28+
* Where a problem happened, as one line.
29+
*
30+
* A module processed by loaders reports its whole request as `moduleName`
31+
* (`babel-loader!./src/app.js`), which reads as noise where the file is what
32+
* matters — so the file comes first and the request follows it in brackets.
33+
* Empty when webpack said neither, rather than a line with nothing on it.
34+
* @param {string | Problem} item a problem, or a message on its own
35+
* @returns {string} the location, or an empty string
36+
*/
37+
export function problemLocation(item) {
38+
if (typeof item === "string") {
39+
return "";
40+
}
41+
42+
const file = item.file || "";
43+
const request = item.moduleName || "";
44+
// `indexOf`, not `includes`: this file is compiled to an ES5 baseline.
45+
const loaded = request.indexOf("!") !== -1;
46+
// The module itself, with the loaders that built it stripped off.
47+
const moduleName = loaded ? request.replace(/^(\s|\S)*!/, "") : request;
48+
49+
if (!moduleName && !file) {
50+
return "";
51+
}
52+
53+
let where = moduleName || file;
54+
55+
// The full request, when loaders made it something other than the module.
56+
if (loaded) {
57+
where += ` (${request})`;
58+
}
59+
60+
// ... and the file, when webpack named one and it is not already what is
61+
// shown. It usually names none, and when it does it is often the module
62+
// itself — appending it either way read as `./a.js (./a.js)`.
63+
if (moduleName && file && file !== moduleName) {
64+
where += ` (${file})`;
65+
}
66+
67+
return `${where}${item.loc ? ` ${item.loc}` : ""}`;
68+
}
69+
70+
/**
71+
* What a problem says, with any stack webpack attached under it.
72+
* @param {string | Problem} item a problem, or a message on its own
73+
* @returns {string} the message
74+
*/
75+
export function problemBody(item) {
76+
if (typeof item === "string") {
77+
return item;
78+
}
79+
80+
let body = item.message || "";
81+
82+
if (Array.isArray(item.stack)) {
83+
// `for...of` needs an array iterator, which an ES5 target does not have.
84+
item.stack.forEach((frame) => {
85+
if (typeof frame === "string") {
86+
body += `\r\n${frame}`;
87+
}
88+
});
89+
}
90+
91+
return body;
92+
}
93+
94+
/**
95+
* A problem as one string, which is what the overlay renders: the location on
96+
* the first line, read as the heading, and the message under it.
97+
* @param {string | Problem} item a problem, or a message on its own
98+
* @returns {string} the problem
99+
*/
100+
export function problemLine(item) {
101+
const location = problemLocation(item);
102+
const body = problemBody(item);
103+
104+
return location ? `${location}\n${body}` : body;
105+
}
106+
107+
/**
108+
* A problem split for a console, where the level belongs in the heading rather
109+
* than being drawn around it.
110+
* @param {string} type `"warning"`, or anything else for an error
111+
* @param {string | Problem} item a problem, or a message on its own
112+
* @returns {{ header: string, body: string }} the problem, in two parts
113+
*/
114+
export function formatProblem(type, item) {
115+
const location = problemLocation(item);
116+
117+
return {
118+
header: `${type === "warning" ? "WARNING" : "ERROR"}${
119+
location ? ` in ${location}` : ""
120+
}`,
121+
body: problemBody(item),
122+
};
123+
}

‎package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@
4141
"types": "./types/client/overlay.d.ts",
4242
"default": "./client/overlay.js"
4343
},
44+
"./client/problem": {
45+
"types": "./types/client/problem.d.ts",
46+
"default": "./client/problem.js"
47+
},
4448
"./package.json": "./package.json"
4549
},
4650
"main": "dist/index.js",

‎src/hot.js‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -388,11 +388,36 @@ function formatErrors(errors) {
388388
return /** @type {string[]} */ (errors);
389389
}
390390

391+
// The same shape the browser runtime builds from an error object, so a
392+
// problem reads the same whether this formatted it or a server sent the
393+
// object over and `client/problem` did. Written out rather than shared:
394+
// this half is CommonJS in node, that half is an ES module in a bundle.
391395
return /** @type {StatsError[]} */ (errors).map((error) => {
392-
const moduleName = error.moduleName || "";
393-
const loc = error.loc || "";
396+
const file = error.file || "";
397+
const request = error.moduleName || "";
398+
const loaded = request.includes("!");
399+
const moduleName = loaded ? request.replace(/^(\s|\S)*!/, "") : request;
394400

395-
return `${moduleName} ${loc}\n${error.message}`;
401+
let where = moduleName || file;
402+
403+
if (where) {
404+
if (loaded) {
405+
where += ` (${request})`;
406+
}
407+
408+
if (moduleName && file && file !== moduleName) {
409+
where += ` (${file})`;
410+
}
411+
412+
if (error.loc) {
413+
where += ` ${error.loc}`;
414+
}
415+
}
416+
417+
// Nothing on the first line rather than a line holding a single space,
418+
// which is what an error webpack names no module for used to send — and
419+
// the overlay reads that first line as the heading.
420+
return where ? `${where}\n${error.message}` : `${error.message}`;
396421
});
397422
}
398423

‎test/e2e/overlay.test.js‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1566,6 +1566,57 @@ describe("overlay shared state across bundled copies (browser)", () => {
15661566
expect(await page.$(`#${OVERLAY_ID}`)).toBeNull();
15671567
});
15681568

1569+
it("takes one of webpack's problems as it comes", async () => {
1570+
await start();
1571+
await page.goto(hotApp.url);
1572+
1573+
// A server that sends error objects to the browser rather than formatting
1574+
// them first has nothing to convert — which is the whole of what
1575+
// webpack-dev-server had to write for itself.
1576+
await page.evaluate(() => {
1577+
globalThis.overlayA.showProblems(
1578+
"errors",
1579+
[
1580+
{
1581+
moduleName: "babel-loader!./src/app.js",
1582+
loc: "3:11",
1583+
message: "Unexpected token",
1584+
stack: [" at parse (babel)"],
1585+
},
1586+
],
1587+
"a",
1588+
);
1589+
});
1590+
1591+
const frame = await overlayFrame();
1592+
const text = await frame.evaluate(() => document.body.textContent);
1593+
1594+
expect(text).toContain("./src/app.js");
1595+
expect(text).toContain("babel-loader!./src/app.js");
1596+
expect(text).toContain("3:11");
1597+
expect(text).toContain("Unexpected token");
1598+
expect(text).toContain("at parse (babel)");
1599+
});
1600+
1601+
it("mixes problems and plain messages in one set", async () => {
1602+
await start();
1603+
await page.goto(hotApp.url);
1604+
1605+
await page.evaluate(() => {
1606+
globalThis.overlayA.showProblems(
1607+
"errors",
1608+
["a plain message", { moduleName: "./src/b.js", message: "an object" }],
1609+
"a",
1610+
);
1611+
});
1612+
1613+
const frame = await overlayFrame();
1614+
1615+
expect(await frame.evaluate(() => document.body.textContent)).toContain(
1616+
"1 / 2",
1617+
);
1618+
});
1619+
15691620
it("dismisses on Escape pressed inside the overlay frame", async () => {
15701621
await start();
15711622
await page.goto(hotApp.url);

‎test/hot.test.js‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import http from "node:http";
22

3+
import { problemLine } from "../client-src/problem";
34
import createHot, {
45
createEventStream,
56
formatErrors,
@@ -152,8 +153,55 @@ describe("hot middleware (unit)", () => {
152153
).toEqual(["./foo.js 1:1\nboom"]);
153154
});
154155

155-
it("tolerates missing moduleName and loc", () => {
156-
expect(formatErrors([{ message: "boom" }])).toEqual([" \nboom"]);
156+
it("says only the message when webpack named no module", () => {
157+
// Not `" \nboom"`: the overlay reads the first line as the heading, so
158+
// a line holding a single space is a heading with nothing in it.
159+
expect(formatErrors([{ message: "boom" }])).toEqual(["boom"]);
160+
expect(formatErrors([{ loc: "main", message: "boom" }])).toEqual([
161+
"boom",
162+
]);
163+
});
164+
165+
it("puts the module first and the loaders that built it after", () => {
166+
expect(
167+
formatErrors([
168+
{ moduleName: "babel-loader!./foo.js", loc: "1:1", message: "boom" },
169+
]),
170+
).toEqual(["./foo.js (babel-loader!./foo.js) 1:1\nboom"]);
171+
});
172+
173+
it("names the file as well, when webpack named a different one", () => {
174+
expect(
175+
formatErrors([
176+
{ moduleName: "./foo.js", file: "./bar.js", message: "boom" },
177+
]),
178+
).toEqual(["./foo.js (./bar.js)\nboom"]);
179+
});
180+
181+
it("does not name the same file twice", () => {
182+
expect(
183+
formatErrors([
184+
{ moduleName: "./foo.js", file: "./foo.js", message: "boom" },
185+
]),
186+
).toEqual(["./foo.js\nboom"]);
187+
expect(formatErrors([{ file: "./foo.js", message: "boom" }])).toEqual([
188+
"./foo.js\nboom",
189+
]);
190+
});
191+
192+
// The browser runtime builds the same shape from an error object a server
193+
// sends over instead of formatting, so the same build has to read the
194+
// same way either way round.
195+
it("agrees with what the browser builds from the same error", () => {
196+
const errors = [
197+
{ moduleName: "./foo.js", loc: "1:1", message: "boom" },
198+
{ moduleName: "babel-loader!./foo.js", message: "boom" },
199+
{ moduleName: "./foo.js", file: "./bar.js", message: "boom" },
200+
{ file: "./foo.js", message: "boom" },
201+
{ loc: "main", message: "boom" },
202+
];
203+
204+
expect(formatErrors(errors)).toEqual(errors.map(problemLine));
157205
});
158206
});
159207

0 commit comments

Comments
 (0)