Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 33 additions & 6 deletions src/content/contribute/plugin-patterns.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,13 @@ W> Since webpack 5, `compilation.fileDependencies`, `compilation.contextDependen

## Changed chunks

Similar to the watch graph, you can monitor changed chunks (or modules, for that matter) within a compilation by tracking their hashes.
Similar to the watch graph, you can monitor changed chunks within a compilation by tracking their content hashes.

W> In webpack 5, `compilation.chunks` is a `Set`, not an array.
Calling `.filter()` or `.map()` directly on it throws a `TypeError`.
Use `for...of` or spread it into an array first.

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.

```js
class MyPlugin {
Expand All @@ -103,15 +109,36 @@ class MyPlugin {

apply(compiler) {
compiler.hooks.emit.tapAsync("MyPlugin", (compilation, callback) => {
const changedChunks = compilation.chunks.filter((chunk) => {
const oldVersion = this.chunkVersions[chunk.name];
this.chunkVersions[chunk.name] = chunk.hash;
return chunk.hash !== oldVersion;
});
const changedChunks = [];

for (const chunk of compilation.chunks) {
const key = chunk.id ?? chunk.name;
const currentHash = chunk.contentHash.javascript;

if (currentHash === undefined) continue;

const oldHash = this.chunkVersions[key];
this.chunkVersions[key] = currentHash;

if (currentHash !== oldHash) {
changedChunks.push(chunk);
}
}

if (changedChunks.length > 0) {
console.log(
"Changed chunks:",
changedChunks.map((chunk) => chunk.id),
);
}

callback();
});
}
}

export default MyPlugin;
```

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.
CSS or other non-JS chunks may not have a `javascript` key in `contentHash` — the `continue` guard skips those safely.
Loading