Skip to content

Commit bb6b909

Browse files
committed
fix(contribute): fix webpack 4 patterns in plugin-patterns Changed chunks section
1 parent 22125dc commit bb6b909

File tree

1 file changed

+33
-6
lines changed

1 file changed

+33
-6
lines changed

src/content/contribute/plugin-patterns.mdx

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,13 @@ W> Since webpack 5, `compilation.fileDependencies`, `compilation.contextDependen
9393

9494
## Changed chunks
9595

96-
Similar to the watch graph, you can monitor changed chunks (or modules, for that matter) within a compilation by tracking their hashes.
96+
Similar to the watch graph, you can monitor changed chunks within a compilation by tracking their content hashes.
97+
98+
W> In webpack 5, `compilation.chunks` is a `Set`, not an array.
99+
Calling `.filter()` or `.map()` directly on it throws a `TypeError`.
100+
Use `for...of` or spread it into an array first.
101+
102+
W> `chunk.hash` was removed in webpack 5. Use `chunk.contentHash.javascript` instead. Using the old property returns `undefined`, causing every chunk to appear changed on every rebuild.
97103

98104
```js
99105
class MyPlugin {
@@ -103,15 +109,36 @@ class MyPlugin {
103109

104110
apply(compiler) {
105111
compiler.hooks.emit.tapAsync("MyPlugin", (compilation, callback) => {
106-
const changedChunks = compilation.chunks.filter((chunk) => {
107-
const oldVersion = this.chunkVersions[chunk.name];
108-
this.chunkVersions[chunk.name] = chunk.hash;
109-
return chunk.hash !== oldVersion;
110-
});
112+
const changedChunks = [];
113+
114+
for (const chunk of compilation.chunks) {
115+
const key = chunk.id ?? chunk.name;
116+
const currentHash = chunk.contentHash.javascript;
117+
118+
if (currentHash === undefined) continue;
119+
120+
const oldHash = this.chunkVersions[key];
121+
this.chunkVersions[key] = currentHash;
122+
123+
if (currentHash !== oldHash) {
124+
changedChunks.push(chunk);
125+
}
126+
}
127+
128+
if (changedChunks.length > 0) {
129+
console.log(
130+
"Changed chunks:",
131+
changedChunks.map((chunk) => chunk.id),
132+
);
133+
}
134+
111135
callback();
112136
});
113137
}
114138
}
115139

116140
export default MyPlugin;
117141
```
142+
143+
T> Use `chunk.id ?? chunk.name` as the tracking key. Some chunks have an `id` but no `name`, so relying on `chunk.name` alone can miss changes.
144+
CSS or other non-JS chunks may not have a `javascript` key in `contentHash` — the `continue` guard skips those safely.

0 commit comments

Comments
 (0)