From 8fd601fde751436f07d5ce166e206780a5340a52 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:10:42 +0000 Subject: [PATCH 01/18] fix: clean the files writeToDisk writes when output.clean is set With writeToDisk as a function, webpack writes to memory and cleans only that, while the middleware copies assets to disk, so the disk was never cleaned. webpack's CleanPlugin is now applied a second time to a view of the compiler whose outputFileSystem is the real one, in standalone and plugin mode. writeToDisk: true already worked: the real file system is the output file system then. Also notes, as TODOs, that the standalone (non-plugin) mode goes in the next major release. Closes #861 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- .changeset/write-to-disk-output-clean.md | 5 + README.md | 2 + src/index.js | 43 +++++ test/write-to-disk-clean.test.js | 225 +++++++++++++++++++++++ types/index.d.ts | 6 + 5 files changed, 281 insertions(+) create mode 100644 .changeset/write-to-disk-output-clean.md create mode 100644 test/write-to-disk-clean.test.js diff --git a/.changeset/write-to-disk-output-clean.md b/.changeset/write-to-disk-output-clean.md new file mode 100644 index 000000000..2e3c94c83 --- /dev/null +++ b/.changeset/write-to-disk-output-clean.md @@ -0,0 +1,5 @@ +--- +"webpack-dev-middleware": patch +--- + +Clean the files `writeToDisk` writes when `output.clean` is set and `writeToDisk` is a function. webpack wrote the build to memory and cleaned only that, so the copies on disk were never cleaned: the previous session's files stayed, and every rebuild left another `main.[contenthash].js` behind. The disk is now cleaned by webpack's own `CleanPlugin` rules, honoring `clean.keep` and `clean.dry`, in plugin mode as in standalone mode. `writeToDisk: true` already worked. diff --git a/README.md b/README.md index e10afcc9e..9b3b6e680 100644 --- a/README.md +++ b/README.md @@ -293,6 +293,8 @@ middleware(compiler, { }); ``` +With either value, [`output.clean`](https://webpack.js.org/configuration/output/#outputclean) cleans the files on disk as it cleans webpack's output: the directory on the first build, the files a rebuild no longer emits after that, with `clean.keep` and `clean.dry` honored. + ### outputFileSystem Type: `Object` diff --git a/src/index.js b/src/index.js index a3c2fc4c9..84da2609a 100644 --- a/src/index.js +++ b/src/index.js @@ -583,6 +583,47 @@ function hookForWriteToDisk(compiler, context) { } /** + * `output.clean` for the files `writeToDisk` copies to the real disk. With a + * function, webpack writes to the in-memory file system and cleans that, while + * the copies on disk were never cleaned: every rebuild left another + * `main.[contenthash].js` behind, and the previous session's files stayed. + * + * webpack's own `CleanPlugin` is applied a second time, to a view of the + * compiler whose `outputFileSystem` is the real one, so the disk is cleaned by + * the same rules as webpack's output: the whole directory on the first build, + * what the last build left behind after that, `clean.keep`, `clean.dry`, the + * `keep` hook other plugins tap, and hot update files kept a little while. + * `writeToDisk: true` needs none of this: the real file system is the output + * file system then, and webpack cleans it itself. + * @param {Compiler} compiler compiler + */ +function cleanDiskForWriteToDisk(compiler) { + const { clean } = compiler.options.output; + + // @ts-expect-error + if (!clean || compiler.hasWebpackDevMiddlewareDiskClean) { + return; + } + + const diskCompiler = Object.create(compiler, { + outputFileSystem: { value: fs }, + }); + + new compiler.webpack.CleanPlugin(clean === true ? {} : clean).apply( + diskCompiler, + ); + + // @ts-expect-error + compiler.hasWebpackDevMiddlewareDiskClean = true; +} + +/** + * TODO in the next major release remove the standalone mode, where the + * middleware starts `compiler.watch()` and prints stats itself, and keep only + * the plugin one, where the host (webpack-cli, webpack-dev-server) owns + * watching and stats, as webpack-dev-server uses it: drop `isPlugin` here and + * `usePlugin` from the framework wrappers, with the watching, `close()` and + * `printStats` paths that exist only for standalone use. * @template {IncomingMessage} [RequestInternal=IncomingMessage] * @template {ServerResponse} [ResponseInternal=ServerResponse] * @param {Compiler | MultiCompiler} compiler compiler @@ -698,6 +739,7 @@ function wdm(compiler, options = {}, isPlugin = false) { if (typeof options.writeToDisk === "function") { for (const compiler of compilersToModify) { hookForWriteToDisk(compiler, context); + cleanDiskForWriteToDisk(compiler); } } @@ -733,6 +775,7 @@ function wdm(compiler, options = {}, isPlugin = false) { } // Start watching, but only for standalone usage, for plugin usage stats will be printed by external code, for example - webpack-cli + // TODO in the next major release remove, with the standalone mode (see `wdm`). if (!isPlugin) { /** * @param {Error | null} err err diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js new file mode 100644 index 000000000..ea28bf14c --- /dev/null +++ b/test/write-to-disk-clean.test.js @@ -0,0 +1,225 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import webpack from "webpack"; + +import middleware from "../src"; + +jest.spyOn(globalThis.console, "log").mockImplementation(); + +// `output.clean` with `writeToDisk`: the files on disk are cleaned as webpack +// cleans its output, in standalone mode and in plugin mode alike — with +// `writeToDisk: true` webpack does it itself, as the real file system is its +// output file system; with a function, webpack writes to memory and the +// middleware copies to disk, so it cleans the disk too. +describe("output.clean with writeToDisk", () => { + /** @type {string} */ + let directory; + /** @type {string} */ + let dist; + + beforeEach(() => { + directory = fs.mkdtempSync(path.join(os.tmpdir(), "wdm-clean-")); + dist = path.join(directory, "dist"); + fs.writeFileSync(path.join(directory, "index.js"), "console.log(1);"); + fs.mkdirSync(path.join(dist, "nested"), { recursive: true }); + // Left from an earlier session, as webpack would find them. + fs.writeFileSync(path.join(dist, "stale.js"), "old"); + fs.writeFileSync(path.join(dist, "nested", "stale.css"), "old"); + }); + + afterEach(() => { + fs.rmSync(directory, { recursive: true, force: true }); + }); + + /** + * @param {import("webpack").Configuration["output"]} output output options + * @returns {import("webpack").Compiler} compiler + */ + function createCompiler(output) { + return webpack({ + mode: "development", + devtool: false, + context: directory, + entry: "./index.js", + output: { path: dist, filename: "main.[contenthash].js", ...output }, + infrastructureLogging: { level: "error" }, + stats: "none", + }); + } + + /** + * @returns {string[]} the files in `dist`, relative to it + */ + function listDist() { + return fs + .readdirSync(dist, { recursive: true, withFileTypes: true }) + .filter((entry) => entry.isFile()) + .map((entry) => + path + .relative(dist, path.join(entry.parentPath, entry.name)) + .replaceAll("\\", "/"), + ) + .toSorted(); + } + + /** + * Start the middleware, standalone or as a plugin with the host watching. + * @param {import("webpack").Compiler} compiler compiler + * @param {import("../src").Options} options options + * @param {boolean} isPlugin plugin mode + * @returns {{ instance: import("../src").API, close: () => Promise }} the middleware and a way to stop it + */ + function start(compiler, options, isPlugin) { + const instance = middleware(compiler, options, isPlugin); + const watching = isPlugin ? compiler.watch({}, () => {}) : undefined; + + return { + instance, + close: () => + new Promise((resolve) => { + if (watching) { + watching.close(resolve); + } else { + instance.close(resolve); + } + }), + }; + } + + /** + * @param {import("../src").API} instance middleware + * @returns {Promise} once the build is done + */ + function built(instance) { + return new Promise((resolve) => { + instance.waitUntilValid(() => resolve()); + }); + } + + /** + * Change the source and wait for the build the watcher starts for it. + * @param {import("webpack").Compiler} compiler compiler + * @returns {Promise} once rebuilt + */ + async function rebuild(compiler) { + const done = new Promise((resolve) => { + compiler.hooks.done.tap("test", () => resolve()); + }); + + // Past the watcher's start, so the change is seen as one. + await new Promise((resolve) => { + setTimeout(resolve, 500); + }); + fs.writeFileSync(path.join(directory, "index.js"), "console.log(2);"); + + await done; + // The middleware writes to disk as the build emits; let it finish. + await new Promise((resolve) => { + setTimeout(resolve, 100); + }); + } + + const writeToDiskValues = [ + ["true", true], + ["a function", () => true], + ]; + + for (const [mode, isPlugin] of [ + ["standalone", false], + ["plugin", true], + ]) { + describe(`in ${mode} mode`, () => { + for (const [label, writeToDisk] of writeToDiskValues) { + it(`cleans the disk on the first build and on a rebuild with "writeToDisk" ${label}`, async () => { + const compiler = createCompiler({ clean: true }); + const { instance, close } = start( + compiler, + { writeToDisk }, + isPlugin, + ); + + try { + await built(instance); + + const first = listDist(); + + expect(first).toHaveLength(1); + expect(first[0]).toMatch(/^main\.[0-9a-f]+\.js$/); + + await rebuild(compiler); + + const second = listDist(); + + expect(second).toHaveLength(1); + expect(second[0]).toMatch(/^main\.[0-9a-f]+\.js$/); + expect(second[0]).not.toBe(first[0]); + } finally { + await close(); + } + }); + } + + it("keeps what `clean.keep` keeps on disk", async () => { + const compiler = createCompiler({ clean: { keep: /\.css$/ } }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true }, + isPlugin, + ); + + try { + await built(instance); + + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + "nested/stale.css", + ]); + } finally { + await close(); + } + }); + + it("removes nothing from disk with `clean.dry`", async () => { + const compiler = createCompiler({ clean: { dry: true } }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true }, + isPlugin, + ); + + try { + await built(instance); + + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + "nested/stale.css", + "stale.js", + ]); + } finally { + await close(); + } + }); + + it("removes nothing from disk without `output.clean`", async () => { + const compiler = createCompiler({}); + const { instance, close } = start( + compiler, + { writeToDisk: () => true }, + isPlugin, + ); + + try { + await built(instance); + await rebuild(compiler); + + // Both builds' bundles, and the earlier session's files. + expect(listDist()).toHaveLength(4); + } finally { + await close(); + } + }); + }); + } +}); diff --git a/types/index.d.ts b/types/index.d.ts index 995090792..ea2490da2 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,5 +1,11 @@ export = wdm; /** + * TODO in the next major release remove the standalone mode, where the + * middleware starts `compiler.watch()` and prints stats itself, and keep only + * the plugin one, where the host (webpack-cli, webpack-dev-server) owns + * watching and stats, as webpack-dev-server uses it: drop `isPlugin` here and + * `usePlugin` from the framework wrappers, with the watching, `close()` and + * `printStats` paths that exist only for standalone use. * @template {IncomingMessage} [RequestInternal=IncomingMessage] * @template {ServerResponse} [ResponseInternal=ServerResponse] * @param {Compiler | MultiCompiler} compiler compiler From 52bed0bd74fbd942802e8431efc2c6cb5db52baf Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:11:37 +0000 Subject: [PATCH 02/18] chore: keep the standalone-mode TODO out of the published types Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- src/index.js | 12 ++++++------ types/index.d.ts | 6 ------ 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/src/index.js b/src/index.js index 84da2609a..02fa63026 100644 --- a/src/index.js +++ b/src/index.js @@ -617,13 +617,13 @@ function cleanDiskForWriteToDisk(compiler) { compiler.hasWebpackDevMiddlewareDiskClean = true; } +// TODO in the next major release remove the standalone mode, where the +// middleware starts `compiler.watch()` and prints stats itself, and keep only +// the plugin one, where the host (webpack-cli, webpack-dev-server) owns +// watching and stats, as webpack-dev-server uses it: drop `isPlugin` here and +// `usePlugin` from the framework wrappers, with the watching, `close()` and +// `printStats` paths that exist only for standalone use. /** - * TODO in the next major release remove the standalone mode, where the - * middleware starts `compiler.watch()` and prints stats itself, and keep only - * the plugin one, where the host (webpack-cli, webpack-dev-server) owns - * watching and stats, as webpack-dev-server uses it: drop `isPlugin` here and - * `usePlugin` from the framework wrappers, with the watching, `close()` and - * `printStats` paths that exist only for standalone use. * @template {IncomingMessage} [RequestInternal=IncomingMessage] * @template {ServerResponse} [ResponseInternal=ServerResponse] * @param {Compiler | MultiCompiler} compiler compiler diff --git a/types/index.d.ts b/types/index.d.ts index ea2490da2..995090792 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,11 +1,5 @@ export = wdm; /** - * TODO in the next major release remove the standalone mode, where the - * middleware starts `compiler.watch()` and prints stats itself, and keep only - * the plugin one, where the host (webpack-cli, webpack-dev-server) owns - * watching and stats, as webpack-dev-server uses it: drop `isPlugin` here and - * `usePlugin` from the framework wrappers, with the watching, `close()` and - * `printStats` paths that exist only for standalone use. * @template {IncomingMessage} [RequestInternal=IncomingMessage] * @template {ServerResponse} [ResponseInternal=ServerResponse] * @param {Compiler | MultiCompiler} compiler compiler From d5c16a9fca8b865f1b40cfc69656896294bdd9a6 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:24:54 +0000 Subject: [PATCH 03/18] fix: write to disk with writeToDisk true and a custom outputFileSystem writeToDisk: true made the real file system webpack's output only when no outputFileSystem was given; with one, it stayed webpack's and nothing was written to disk at all. Copy assets to disk then too, as a function does, and clean them with output.clean. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- .changeset/write-to-disk-output-clean.md | 2 +- README.md | 2 +- src/index.js | 15 ++++++++++++--- test/write-to-disk-clean.test.js | 24 ++++++++++++++++++++++++ 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/.changeset/write-to-disk-output-clean.md b/.changeset/write-to-disk-output-clean.md index 2e3c94c83..125d37866 100644 --- a/.changeset/write-to-disk-output-clean.md +++ b/.changeset/write-to-disk-output-clean.md @@ -2,4 +2,4 @@ "webpack-dev-middleware": patch --- -Clean the files `writeToDisk` writes when `output.clean` is set and `writeToDisk` is a function. webpack wrote the build to memory and cleaned only that, so the copies on disk were never cleaned: the previous session's files stayed, and every rebuild left another `main.[contenthash].js` behind. The disk is now cleaned by webpack's own `CleanPlugin` rules, honoring `clean.keep` and `clean.dry`, in plugin mode as in standalone mode. `writeToDisk: true` already worked. +Clean the files `writeToDisk` writes when `output.clean` is set and `writeToDisk` is a function. webpack wrote the build to memory and cleaned only that, so the copies on disk were never cleaned: the previous session's files stayed, and every rebuild left another `main.[contenthash].js` behind. The disk is now cleaned by webpack's own `CleanPlugin` rules, honoring `clean.keep` and `clean.dry`, in plugin mode as in standalone mode. `writeToDisk: true` already worked. `writeToDisk: true` with an `outputFileSystem` of your own now writes to disk too: it wrote nothing there before. diff --git a/README.md b/README.md index 9b3b6e680..74acb8f64 100644 --- a/README.md +++ b/README.md @@ -301,7 +301,7 @@ Type: `Object` Default: [memfs](https://github.com/streamich/memfs) Set the default file system which will be used by webpack as primary destination of generated files. -This option isn't affected by the [writeToDisk](#writeToDisk) option. +This option isn't affected by the [writeToDisk](#writeToDisk) option. With `writeToDisk` set, files are written to it as before and also copied to disk — with `true` as with a function. You have to provide `.join()` and `mkdirp` method to the `outputFileSystem` instance manually for compatibility with `webpack@4`. diff --git a/src/index.js b/src/index.js index 02fa63026..b01b16dd3 100644 --- a/src/index.js +++ b/src/index.js @@ -593,8 +593,8 @@ function hookForWriteToDisk(compiler, context) { * the same rules as webpack's output: the whole directory on the first build, * what the last build left behind after that, `clean.keep`, `clean.dry`, the * `keep` hook other plugins tap, and hot update files kept a little while. - * `writeToDisk: true` needs none of this: the real file system is the output - * file system then, and webpack cleans it itself. + * `writeToDisk: true` on its own needs none of this: the real file system is + * the output file system then, and webpack cleans it itself. * @param {Compiler} compiler compiler */ function cleanDiskForWriteToDisk(compiler) { @@ -736,7 +736,16 @@ function wdm(compiler, options = {}, isPlugin = false) { ); } - if (typeof options.writeToDisk === "function") { + // Copied to disk whenever webpack does not write there itself: always for a + // function, which filters what is copied, and for `true` when an + // `outputFileSystem` of your own is webpack's, as it then stays — before, + // `writeToDisk: true` with one wrote nothing to disk at all. + if ( + typeof options.writeToDisk === "function" || + (options.writeToDisk === true && + options.outputFileSystem && + options.outputFileSystem !== fs) + ) { for (const compiler of compilersToModify) { hookForWriteToDisk(compiler, context); cleanDiskForWriteToDisk(compiler); diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index ea28bf14c..8bd3dc33f 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -2,6 +2,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { Volume, createFsFromVolume } from "memfs"; import webpack from "webpack"; import middleware from "../src"; @@ -161,6 +162,29 @@ describe("output.clean with writeToDisk", () => { }); } + it('writes to disk, and cleans it, with "writeToDisk" true and an "outputFileSystem" of your own', async () => { + const compiler = createCompiler({ clean: true }); + const { instance, close } = start( + compiler, + { + writeToDisk: true, + outputFileSystem: createFsFromVolume(new Volume()), + }, + isPlugin, + ); + + try { + await built(instance); + + // Before, nothing reached the disk at all: only the stale files. + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + ]); + } finally { + await close(); + } + }); + it("keeps what `clean.keep` keeps on disk", async () => { const compiler = createCompiler({ clean: { keep: /\.css$/ } }); const { instance, close } = start( From a2a28e9346279db064f3ac00e8793514bcf2bf8c Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:26:19 +0000 Subject: [PATCH 04/18] test: list the output without Dirent#parentPath Dirent#parentPath arrived in Node.js 20.12; this package supports 20.9. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- test/write-to-disk-clean.test.js | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index 8bd3dc33f..76ae39cd8 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -54,14 +54,12 @@ describe("output.clean with writeToDisk", () => { * @returns {string[]} the files in `dist`, relative to it */ function listDist() { + // Paths as strings rather than `Dirent`s: `Dirent#parentPath` is newer + // than the oldest Node.js this package supports. return fs - .readdirSync(dist, { recursive: true, withFileTypes: true }) - .filter((entry) => entry.isFile()) - .map((entry) => - path - .relative(dist, path.join(entry.parentPath, entry.name)) - .replaceAll("\\", "/"), - ) + .readdirSync(dist, { recursive: true, encoding: "utf8" }) + .filter((file) => fs.statSync(path.join(dist, file)).isFile()) + .map((file) => file.replaceAll("\\", "/")) .toSorted(); } From c0fe374bd3e1c47603b38f225de510c47d952b54 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:37:35 +0000 Subject: [PATCH 05/18] test: cover copy-webpack-plugin with writeToDisk and output.clean Copied files reach the disk beside the bundle, survive rebuilds, are copied again when changed and cleaned once no longer copied, with writeToDisk true and a function, in standalone and plugin mode; a filter leaving them off disk still serves them from memory. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- package-lock.json | 48 +++++++++++ package.json | 1 + test/write-to-disk-clean.test.js | 138 ++++++++++++++++++++++++++++++- 3 files changed, 184 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 10db8bf9c..140e1605f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -36,6 +36,7 @@ "babel-loader": "^10.1.1", "babel-plugin-istanbul": "^8.0.0", "connect": "^3.7.0", + "copy-webpack-plugin": "^14.0.0", "cspell": "^10.2.0", "deepmerge": "^4.3.1", "del-cli": "^8.0.1", @@ -9445,6 +9446,43 @@ "node": ">= 0.8" } }, + "node_modules/copy-webpack-plugin": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/copy-webpack-plugin/-/copy-webpack-plugin-14.0.0.tgz", + "integrity": "sha512-3JLW90aBGeaTLpM7mYQKpnVdgsUZRExY55giiZgLuX/xTQRUs1dOCwbBnWnvY6Q6rfZoXMNwzOQJCSZPppfqXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "glob-parent": "^6.0.1", + "normalize-path": "^3.0.0", + "schema-utils": "^4.2.0", + "serialize-javascript": "^7.0.3", + "tinyglobby": "^0.2.12" + }, + "engines": { + "node": ">= 20.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + } + }, + "node_modules/copy-webpack-plugin/node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/core-js-compat": { "version": "3.50.0", "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.50.0.tgz", @@ -18993,6 +19031,16 @@ "url": "https://opencollective.com/express" } }, + "node_modules/serialize-javascript": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.4.tgz", + "integrity": "sha512-FqlEuoTq/zRmA4Lg6aOqyH3lCHbUtCB0bmHCeFniX2GBdDqMJM3FwdvEhlE5Pim1dlt2FfBdVPmUNNiGhhKqpw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/serve-static": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", diff --git a/package.json b/package.json index f5f698ab2..b3982a284 100644 --- a/package.json +++ b/package.json @@ -115,6 +115,7 @@ "babel-loader": "^10.1.1", "babel-plugin-istanbul": "^8.0.0", "connect": "^3.7.0", + "copy-webpack-plugin": "^14.0.0", "cspell": "^10.2.0", "deepmerge": "^4.3.1", "del-cli": "^8.0.1", diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index 76ae39cd8..ec8c35a2c 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -2,6 +2,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import CopyPlugin from "copy-webpack-plugin"; import { Volume, createFsFromVolume } from "memfs"; import webpack from "webpack"; @@ -36,15 +37,17 @@ describe("output.clean with writeToDisk", () => { /** * @param {import("webpack").Configuration["output"]} output output options + * @param {import("webpack").Configuration["plugins"]=} plugins plugins * @returns {import("webpack").Compiler} compiler */ - function createCompiler(output) { + function createCompiler(output, plugins = []) { return webpack({ mode: "development", devtool: false, context: directory, entry: "./index.js", output: { path: dist, filename: "main.[contenthash].js", ...output }, + plugins, infrastructureLogging: { level: "error" }, stats: "none", }); @@ -100,9 +103,14 @@ describe("output.clean with writeToDisk", () => { /** * Change the source and wait for the build the watcher starts for it. * @param {import("webpack").Compiler} compiler compiler + * @param {() => void=} change the change, the entry's source by default * @returns {Promise} once rebuilt */ - async function rebuild(compiler) { + async function rebuild( + compiler, + change = () => + fs.writeFileSync(path.join(directory, "index.js"), "console.log(2);"), + ) { const done = new Promise((resolve) => { compiler.hooks.done.tap("test", () => resolve()); }); @@ -111,7 +119,7 @@ describe("output.clean with writeToDisk", () => { await new Promise((resolve) => { setTimeout(resolve, 500); }); - fs.writeFileSync(path.join(directory, "index.js"), "console.log(2);"); + change(); await done; // The middleware writes to disk as the build emits; let it finish. @@ -120,6 +128,45 @@ describe("output.clean with writeToDisk", () => { }); } + /** + * @param {string} file a file in `dist` + * @returns {string} its path + */ + function inDist(file) { + return path.join(dist, file); + } + + /** + * @param {string} file a file in `dist` + * @returns {string} its content + */ + function readDist(file) { + return fs.readFileSync(inDist(file), "utf8"); + } + + /** + * @param {string} file a file in `public` + * @param {string=} content its new content, or none to remove it + */ + function changePublic(file, content) { + const target = path.join(directory, "public", file); + + if (typeof content === "string") { + fs.writeFileSync(target, content); + } else { + fs.rmSync(target); + } + } + + /** + * Create `public`, for copy-webpack-plugin to copy to the output. + */ + function createPublic() { + fs.mkdirSync(path.join(directory, "public", "images"), { recursive: true }); + changePublic("robots.txt", "v1"); + changePublic("images/logo.svg", ""); + } + const writeToDiskValues = [ ["true", true], ["a function", () => true], @@ -242,6 +289,91 @@ describe("output.clean with writeToDisk", () => { await close(); } }); + + describe("with copy-webpack-plugin", () => { + beforeEach(createPublic); + + /** + * @returns {import("webpack").Compiler} compiler copying `public` to the output + */ + function createCopyingCompiler() { + return createCompiler({ clean: true }, [ + new CopyPlugin({ patterns: [{ from: "public" }] }), + ]); + } + + for (const [label, writeToDisk] of writeToDiskValues) { + it(`writes the copied files to disk and keeps them clean with "writeToDisk" ${label}`, async () => { + const compiler = createCopyingCompiler(); + const { instance, close } = start( + compiler, + { writeToDisk }, + isPlugin, + ); + const bundle = expect.stringMatching(/^main\.[0-9a-f]+\.js$/); + + try { + await built(instance); + + // The copied files beside the bundle, the stale ones gone. + expect(listDist()).toEqual([ + "images/logo.svg", + bundle, + "robots.txt", + ]); + + // A rebuild of the bundle leaves what is still copied. + const [, firstBundle] = listDist(); + + await rebuild(compiler); + + expect(listDist()).toEqual([ + "images/logo.svg", + bundle, + "robots.txt", + ]); + expect(listDist()[1]).not.toBe(firstBundle); + + // A changed file is copied again. + await rebuild(compiler, () => changePublic("robots.txt", "v2")); + + expect(readDist("robots.txt")).toBe("v2"); + + // One no longer copied is cleaned. + await rebuild(compiler, () => changePublic("images/logo.svg")); + + expect(listDist()).toEqual([bundle, "robots.txt"]); + } finally { + await close(); + } + }); + } + + it("leaves the copied files off disk when the function does not write them", async () => { + const compiler = createCopyingCompiler(); + const { instance, close } = start( + compiler, + { writeToDisk: (targetPath) => targetPath.endsWith(".js") }, + isPlugin, + ); + + try { + await built(instance); + + // Served from memory, never written, and the stale files cleaned. + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + ]); + expect( + instance.context.outputFileSystem + .readFileSync(inDist("robots.txt")) + .toString(), + ).toBe("v1"); + } finally { + await close(); + } + }); + }); }); } }); From 904f5586ed27449bf704b241605a202a7c39ef54 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:39:11 +0000 Subject: [PATCH 06/18] fix: skip disk cleaning for compilers without webpack's CleanPlugin Rspack cleans natively and exposes no CleanPlugin to apply again, so the middleware failed to start there with output.clean and a writeToDisk function; it now writes to disk without cleaning, as before. Also fix the writeToDisk anchor in the README. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- README.md | 2 +- src/index.js | 10 ++++++++++ test/write-to-disk-clean.test.js | 24 ++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 74acb8f64..a9ed652d6 100644 --- a/README.md +++ b/README.md @@ -301,7 +301,7 @@ Type: `Object` Default: [memfs](https://github.com/streamich/memfs) Set the default file system which will be used by webpack as primary destination of generated files. -This option isn't affected by the [writeToDisk](#writeToDisk) option. With `writeToDisk` set, files are written to it as before and also copied to disk — with `true` as with a function. +This option isn't affected by the [writeToDisk](#writetodisk) option. With `writeToDisk` set, files are written to it as before and also copied to disk — with `true` as with a function. You have to provide `.join()` and `mkdirp` method to the `outputFileSystem` instance manually for compatibility with `webpack@4`. diff --git a/src/index.js b/src/index.js index b01b16dd3..6b676e114 100644 --- a/src/index.js +++ b/src/index.js @@ -595,6 +595,9 @@ function hookForWriteToDisk(compiler, context) { * `keep` hook other plugins tap, and hot update files kept a little while. * `writeToDisk: true` on its own needs none of this: the real file system is * the output file system then, and webpack cleans it itself. + * + * Rspack cleans natively and has no such plugin to apply again, so there the + * copies on disk are left as before rather than failing to start. * @param {Compiler} compiler compiler */ function cleanDiskForWriteToDisk(compiler) { @@ -605,6 +608,13 @@ function cleanDiskForWriteToDisk(compiler) { return; } + if ( + "rspack" in compiler || + typeof compiler.webpack?.CleanPlugin !== "function" + ) { + return; + } + const diskCompiler = Object.create(compiler, { outputFileSystem: { value: fs }, }); diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index ec8c35a2c..5fc056f51 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -290,6 +290,30 @@ describe("output.clean with writeToDisk", () => { } }); + it("writes to disk without cleaning it when the compiler has no `CleanPlugin`, as with Rspack", async () => { + const compiler = createCompiler({ clean: true }); + + compiler.webpack = { ...compiler.webpack, CleanPlugin: undefined }; + + const { instance, close } = start( + compiler, + { writeToDisk: () => true }, + isPlugin, + ); + + try { + await built(instance); + + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + "nested/stale.css", + "stale.js", + ]); + } finally { + await close(); + } + }); + describe("with copy-webpack-plugin", () => { beforeEach(createPublic); From 05e2215f0b46223eb697ea80f691b1de719f10db Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:53:40 +0000 Subject: [PATCH 07/18] fix: clean disk copies the writeToDisk function skips The disk cleaner saw every asset of the build, so a file the function skips was kept on disk from an earlier session despite output.clean. It now sees only the assets the function writes, while webpack's own cleaner still sees them all, and other plugins' keep hook still applies. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- src/index.js | 66 +++++++++++++++++++++++++++++--- test/write-to-disk-clean.test.js | 6 ++- 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/src/index.js b/src/index.js index 6b676e114..e9b2bf6ce 100644 --- a/src/index.js +++ b/src/index.js @@ -596,11 +596,19 @@ function hookForWriteToDisk(compiler, context) { * `writeToDisk: true` on its own needs none of this: the real file system is * the output file system then, and webpack cleans it itself. * + * The disk cleaner sees only the assets the `writeToDisk` function writes, so + * a file it skips is cleaned from disk like any other the build no longer + * writes there, rather than kept from an earlier session; webpack's own + * cleaner still sees them all. + * * Rspack cleans natively and has no such plugin to apply again, so there the * copies on disk are left as before rather than failing to start. + * @template {IncomingMessage} Request + * @template {ServerResponse} Response * @param {Compiler} compiler compiler + * @param {WithOptional, "watching" | "outputFileSystem">} context context */ -function cleanDiskForWriteToDisk(compiler) { +function cleanDiskForWriteToDisk(compiler, context) { const { clean } = compiler.options.output; // @ts-expect-error @@ -615,13 +623,61 @@ function cleanDiskForWriteToDisk(compiler) { return; } + const { CleanPlugin } = compiler.webpack; + + /** + * @param {import("webpack").Compilation} compilation compilation + * @returns {import("webpack").Compilation} a view of it with only the assets written to disk + */ + const writtenToDisk = (compilation) => { + const { writeToDisk: filter } = context.options; + + if (typeof filter !== "function") { + return compilation; + } + + const outputPath = compilation.getPath(compiler.outputPath, {}); + /** @type {import("webpack").Compilation["assets"]} */ + const assets = {}; + + for (const [name, source] of Object.entries(compilation.assets)) { + if (filter(path.join(outputPath, name))) { + assets[name] = source; + } + } + + const view = Object.create(compilation, { assets: { value: assets } }); + + // What other plugins keep through the `keep` hook is kept on disk too. + CleanPlugin.getCompilationHooks(view).keep.tap(PLUGIN_NAME, (file) => + CleanPlugin.getCompilationHooks(compilation).keep.call(file), + ); + + return view; + }; + const diskCompiler = Object.create(compiler, { outputFileSystem: { value: fs }, + hooks: { + value: Object.create(compiler.hooks, { + emit: { + value: { + /** + * @param {Parameters[0]} options options + * @param {(compilation: import("webpack").Compilation, callback: (err?: Error | null) => void) => void} fn fn + * @returns {void} + */ + tapAsync: (options, fn) => + compiler.hooks.emit.tapAsync(options, (compilation, callback) => + fn(writtenToDisk(compilation), callback), + ), + }, + }, + }), + }, }); - new compiler.webpack.CleanPlugin(clean === true ? {} : clean).apply( - diskCompiler, - ); + new CleanPlugin(clean === true ? {} : clean).apply(diskCompiler); // @ts-expect-error compiler.hasWebpackDevMiddlewareDiskClean = true; @@ -758,7 +814,7 @@ function wdm(compiler, options = {}, isPlugin = false) { ) { for (const compiler of compilersToModify) { hookForWriteToDisk(compiler, context); - cleanDiskForWriteToDisk(compiler); + cleanDiskForWriteToDisk(compiler, context); } } diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index 5fc056f51..70206ba6b 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -374,6 +374,9 @@ describe("output.clean with writeToDisk", () => { } it("leaves the copied files off disk when the function does not write them", async () => { + // One of them on disk from an earlier session, to be cleaned. + fs.writeFileSync(inDist("robots.txt"), "old"); + const compiler = createCopyingCompiler(); const { instance, close } = start( compiler, @@ -384,7 +387,8 @@ describe("output.clean with writeToDisk", () => { try { await built(instance); - // Served from memory, never written, and the stale files cleaned. + // Served from memory, never written, and the stale files cleaned, the + // earlier copy of one the function skips too. expect(listDist()).toEqual([ expect.stringMatching(/^main\.[0-9a-f]+\.js$/), ]); From f56170bdc4eb72a7082d41450e7012ea65a8e570 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:08:52 +0000 Subject: [PATCH 08/18] fix: clean disk copies of assets named with a query string webpack writes `lazy.js?[contenthash]` as `lazy.js`, but the disk cleaner filtered and tracked the name with the query, so the filter saw the wrong path and the file stayed on disk once the asset was gone. Strip the query or hash as webpack does before filtering and cleaning. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- src/index.js | 22 +++++++++++++--- test/write-to-disk-clean.test.js | 44 ++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 3 deletions(-) diff --git a/src/index.js b/src/index.js index e9b2bf6ce..38dd64836 100644 --- a/src/index.js +++ b/src/index.js @@ -639,14 +639,30 @@ function cleanDiskForWriteToDisk(compiler, context) { const outputPath = compilation.getPath(compiler.outputPath, {}); /** @type {import("webpack").Compilation["assets"]} */ const assets = {}; + /** @type {import("webpack").Compilation["assetsInfo"]} */ + const assetsInfo = new Map(); for (const [name, source] of Object.entries(compilation.assets)) { - if (filter(path.join(outputPath, name))) { - assets[name] = source; + // As webpack writes it: `main.js?[contenthash]` is `main.js` on disk. + const queryOrHashIndex = name.search(/[?#]/); + const file = + queryOrHashIndex >= 0 ? name.slice(0, queryOrHashIndex) : name; + + if (filter(path.join(outputPath, file))) { + assets[file] = source; + + const info = compilation.assetsInfo.get(name); + + if (info) { + assetsInfo.set(file, info); + } } } - const view = Object.create(compilation, { assets: { value: assets } }); + const view = Object.create(compilation, { + assets: { value: assets }, + assetsInfo: { value: assetsInfo }, + }); // What other plugins keep through the `keep` hook is kept on disk too. CleanPlugin.getCompilationHooks(view).keep.tap(PLUGIN_NAME, (file) => diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index 70206ba6b..93a377383 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -144,6 +144,14 @@ describe("output.clean with writeToDisk", () => { return fs.readFileSync(inDist(file), "utf8"); } + /** + * @param {string} file a source file + * @param {string} content its content + */ + function writeSource(file, content) { + fs.writeFileSync(path.join(directory, file), content); + } + /** * @param {string} file a file in `public` * @param {string=} content its new content, or none to remove it @@ -290,6 +298,42 @@ describe("output.clean with writeToDisk", () => { } }); + it("cleans from disk a chunk named with a query string once it is gone", async () => { + writeSource( + "index.js", + 'import(/* webpackChunkName: "lazy" */ "./lazy.js");', + ); + writeSource("lazy.js", "console.log(1);"); + + const compiler = createCompiler({ + clean: true, + chunkFilename: "[name].js?[contenthash]", + }); + const { instance, close } = start( + compiler, + { writeToDisk: (targetPath) => targetPath.endsWith(".js") }, + isPlugin, + ); + + try { + await built(instance); + + expect(listDist()).toEqual([ + "lazy.js", + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + ]); + + // The entry no longer imports it, so the chunk is gone. + await rebuild(compiler); + + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + ]); + } finally { + await close(); + } + }); + it("writes to disk without cleaning it when the compiler has no `CleanPlugin`, as with Rspack", async () => { const compiler = createCompiler({ clean: true }); From 8ad3c999bbe62fa43bdfea34319560ce92d86205 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:10:42 +0000 Subject: [PATCH 09/18] test: wait for the build after the change in write-to-disk clean tests On macOS the watcher may run one more build for the files the test wrote before it started; the rebuild helper took that build's done for the one after the change. Wait for a build started after the change instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- test/write-to-disk-clean.test.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index 93a377383..34aef11b0 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -111,8 +111,16 @@ describe("output.clean with writeToDisk", () => { change = () => fs.writeFileSync(path.join(directory, "index.js"), "console.log(2);"), ) { + /** @type {number} */ + let changedAt = Infinity; + // The build that started after the change: the watcher may run one more + // for the files the test wrote before it started, as on macOS. const done = new Promise((resolve) => { - compiler.hooks.done.tap("test", () => resolve()); + compiler.hooks.done.tap("test", (stats) => { + if (stats.startTime >= changedAt) { + resolve(); + } + }); }); // Past the watcher's start, so the change is seen as one. @@ -120,6 +128,7 @@ describe("output.clean with writeToDisk", () => { setTimeout(resolve, 500); }); change(); + changedAt = Date.now(); await done; // The middleware writes to disk as the build emits; let it finish. From 5ff497ef192028761556f0badfbaa5b55154bd16 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:45:35 +0000 Subject: [PATCH 10/18] refactor: write to disk through webpack's additionalOutputs hook Replace the disk cleaner, which applied CleanPlugin again to views of the compiler and compilation, with webpack's own support for more outputs: where compiler.hooks.additionalOutputs exists, writeToDisk adds the disk as one, so webpack writes links, permissions, times and query-named assets there as to its own output, and output.clean cleans it too. With an older webpack or Rspack the middleware copies to disk as before. Cover output.copy beside copy-webpack-plugin, and a copied link and its permissions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- .changeset/write-to-disk-output-clean.md | 2 +- README.md | 4 +- src/index.js | 142 ++----- test/write-to-disk-clean.test.js | 516 ++++++++++++++--------- 4 files changed, 356 insertions(+), 308 deletions(-) diff --git a/.changeset/write-to-disk-output-clean.md b/.changeset/write-to-disk-output-clean.md index 125d37866..d19d6e6ab 100644 --- a/.changeset/write-to-disk-output-clean.md +++ b/.changeset/write-to-disk-output-clean.md @@ -2,4 +2,4 @@ "webpack-dev-middleware": patch --- -Clean the files `writeToDisk` writes when `output.clean` is set and `writeToDisk` is a function. webpack wrote the build to memory and cleaned only that, so the copies on disk were never cleaned: the previous session's files stayed, and every rebuild left another `main.[contenthash].js` behind. The disk is now cleaned by webpack's own `CleanPlugin` rules, honoring `clean.keep` and `clean.dry`, in plugin mode as in standalone mode. `writeToDisk: true` already worked. `writeToDisk: true` with an `outputFileSystem` of your own now writes to disk too: it wrote nothing there before. +Clean the files `writeToDisk` writes when `output.clean` is set and `writeToDisk` is a function. webpack wrote the build to memory and cleaned only that, so the copies on disk were never cleaned: the previous session's files stayed, and every rebuild left another `main.[contenthash].js` behind. With webpack 5.113.0 or later the middleware adds the disk as an additional output (`compiler.hooks.additionalOutputs`), so webpack writes the files there itself, links, permissions and times included, and `output.clean` cleans the disk too, honoring `clean.keep` and `clean.dry`, in plugin mode as in standalone mode; with an older webpack or Rspack the middleware copies to disk as before. `writeToDisk: true` with an `outputFileSystem` of your own now writes to disk too: it wrote nothing there before. diff --git a/README.md b/README.md index a9ed652d6..0d2a31c0c 100644 --- a/README.md +++ b/README.md @@ -293,7 +293,7 @@ middleware(compiler, { }); ``` -With either value, [`output.clean`](https://webpack.js.org/configuration/output/#outputclean) cleans the files on disk as it cleans webpack's output: the directory on the first build, the files a rebuild no longer emits after that, with `clean.keep` and `clean.dry` honored. +With either value, [`output.clean`](https://webpack.js.org/configuration/output/#outputclean) cleans the files on disk as it cleans webpack's output: the directory on the first build, the files a rebuild no longer emits after that, with `clean.keep` and `clean.dry` honored. With a function, webpack writes the files it takes to disk as it writes its own output, links, permissions and times included, which needs webpack 5.113.0 or later; with an older webpack or Rspack the middleware copies them to disk itself, and they are not cleaned. ### outputFileSystem @@ -301,7 +301,7 @@ Type: `Object` Default: [memfs](https://github.com/streamich/memfs) Set the default file system which will be used by webpack as primary destination of generated files. -This option isn't affected by the [writeToDisk](#writetodisk) option. With `writeToDisk` set, files are written to it as before and also copied to disk — with `true` as with a function. +This option isn't affected by the [writeToDisk](#writetodisk) option. With `writeToDisk` set, files are written to it as before and also to disk — with `true` as with a function. You have to provide `.join()` and `mkdirp` method to the `outputFileSystem` instance manually for compatibility with `webpack@4`. diff --git a/src/index.js b/src/index.js index 38dd64836..c64954413 100644 --- a/src/index.js +++ b/src/index.js @@ -583,120 +583,55 @@ function hookForWriteToDisk(compiler, context) { } /** - * `output.clean` for the files `writeToDisk` copies to the real disk. With a - * function, webpack writes to the in-memory file system and cleans that, while - * the copies on disk were never cleaned: every rebuild left another - * `main.[contenthash].js` behind, and the previous session's files stayed. - * - * webpack's own `CleanPlugin` is applied a second time, to a view of the - * compiler whose `outputFileSystem` is the real one, so the disk is cleaned by - * the same rules as webpack's output: the whole directory on the first build, - * what the last build left behind after that, `clean.keep`, `clean.dry`, the - * `keep` hook other plugins tap, and hot update files kept a little while. - * `writeToDisk: true` on its own needs none of this: the real file system is - * the output file system then, and webpack cleans it itself. - * - * The disk cleaner sees only the assets the `writeToDisk` function writes, so - * a file it skips is cleaned from disk like any other the build no longer - * writes there, rather than kept from an earlier session; webpack's own - * cleaner still sees them all. - * - * Rspack cleans natively and has no such plugin to apply again, so there the - * copies on disk are left as before rather than failing to start. + * Has webpack write to the real disk what `writeToDisk` takes, besides its + * own output file system, where webpack supports more outputs: it then writes + * links, permissions and times there as it does to its own, and `output.clean` + * cleans the disk too. Rspack and webpack before 5.113.0 have no such hook, so + * there the middleware copies to disk itself, which is never cleaned. * @template {IncomingMessage} Request * @template {ServerResponse} Response * @param {Compiler} compiler compiler * @param {WithOptional, "watching" | "outputFileSystem">} context context + * @returns {boolean} true when webpack writes to disk, otherwise false */ -function cleanDiskForWriteToDisk(compiler, context) { - const { clean } = compiler.options.output; +function addDiskOutput(compiler, context) { + const { additionalOutputs } = + /** @type {Compiler["hooks"] & { additionalOutputs?: import("tapable").SyncHook<[Set<{ outputFileSystem: OutputFileSystem, test?: (targetPath: string) => boolean }>]> }} */ ( + compiler.hooks + ); - // @ts-expect-error - if (!clean || compiler.hasWebpackDevMiddlewareDiskClean) { - return; + if (!additionalOutputs) { + return false; } - if ( - "rspack" in compiler || - typeof compiler.webpack?.CleanPlugin !== "function" - ) { - return; + // @ts-expect-error + if (compiler.hasWebpackDevMiddlewareDiskOutput) { + return true; } - const { CleanPlugin } = compiler.webpack; - - /** - * @param {import("webpack").Compilation} compilation compilation - * @returns {import("webpack").Compilation} a view of it with only the assets written to disk - */ - const writtenToDisk = (compilation) => { - const { writeToDisk: filter } = context.options; - - if (typeof filter !== "function") { - return compilation; - } - - const outputPath = compilation.getPath(compiler.outputPath, {}); - /** @type {import("webpack").Compilation["assets"]} */ - const assets = {}; - /** @type {import("webpack").Compilation["assetsInfo"]} */ - const assetsInfo = new Map(); - - for (const [name, source] of Object.entries(compilation.assets)) { - // As webpack writes it: `main.js?[contenthash]` is `main.js` on disk. - const queryOrHashIndex = name.search(/[?#]/); - const file = - queryOrHashIndex >= 0 ? name.slice(0, queryOrHashIndex) : name; - - if (filter(path.join(outputPath, file))) { - assets[file] = source; - - const info = compilation.assetsInfo.get(name); - - if (info) { - assetsInfo.set(file, info); - } - } - } - - const view = Object.create(compilation, { - assets: { value: assets }, - assetsInfo: { value: assetsInfo }, - }); - - // What other plugins keep through the `keep` hook is kept on disk too. - CleanPlugin.getCompilationHooks(view).keep.tap(PLUGIN_NAME, (file) => - CleanPlugin.getCompilationHooks(compilation).keep.call(file), - ); + const output = { + outputFileSystem: /** @type {OutputFileSystem} */ ( + /** @type {unknown} */ (fs) + ), + /** + * @param {string} targetPath absolute path of the asset + * @returns {boolean} true when the asset is written to disk + */ + test: (targetPath) => { + const { writeToDisk: filter } = context.options; - return view; + return typeof filter === "function" ? filter(targetPath) : true; + }, }; - const diskCompiler = Object.create(compiler, { - outputFileSystem: { value: fs }, - hooks: { - value: Object.create(compiler.hooks, { - emit: { - value: { - /** - * @param {Parameters[0]} options options - * @param {(compilation: import("webpack").Compilation, callback: (err?: Error | null) => void) => void} fn fn - * @returns {void} - */ - tapAsync: (options, fn) => - compiler.hooks.emit.tapAsync(options, (compilation, callback) => - fn(writtenToDisk(compilation), callback), - ), - }, - }, - }), - }, + additionalOutputs.tap(PLUGIN_NAME, (outputs) => { + outputs.add(output); }); - new CleanPlugin(clean === true ? {} : clean).apply(diskCompiler); - // @ts-expect-error - compiler.hasWebpackDevMiddlewareDiskClean = true; + compiler.hasWebpackDevMiddlewareDiskOutput = true; + + return true; } // TODO in the next major release remove the standalone mode, where the @@ -818,10 +753,12 @@ function wdm(compiler, options = {}, isPlugin = false) { ); } - // Copied to disk whenever webpack does not write there itself: always for a - // function, which filters what is copied, and for `true` when an + // Written to disk besides webpack's own output file system: always for a + // function, which filters what is written, and for `true` when an // `outputFileSystem` of your own is webpack's, as it then stays — before, // `writeToDisk: true` with one wrote nothing to disk at all. + // TODO in the next major release require a webpack with `additionalOutputs` + // and drop `hookForWriteToDisk`, the copy to disk for those without it. if ( typeof options.writeToDisk === "function" || (options.writeToDisk === true && @@ -829,8 +766,9 @@ function wdm(compiler, options = {}, isPlugin = false) { options.outputFileSystem !== fs) ) { for (const compiler of compilersToModify) { - hookForWriteToDisk(compiler, context); - cleanDiskForWriteToDisk(compiler, context); + if (!addDiskOutput(compiler, context)) { + hookForWriteToDisk(compiler, context); + } } } diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index 34aef11b0..5b1c272e2 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -10,11 +10,24 @@ import middleware from "../src"; jest.spyOn(globalThis.console, "log").mockImplementation(); +// Where webpack writes to more outputs than its own, `writeToDisk` adds the +// real disk as one, and `output.clean` cleans it as webpack's own output. +const hasAdditionalOutputs = "additionalOutputs" in webpack({}).hooks; +const describeWithAdditionalOutputs = hasAdditionalOutputs + ? describe + : describe.skip; +const describeWithoutAdditionalOutputs = hasAdditionalOutputs + ? describe.skip + : describe; +// Links and permissions need privileges or mean nothing on Windows. +const describeWithLinksAndPermissions = + os.platform() === "win32" ? describe.skip : describe; + // `output.clean` with `writeToDisk`: the files on disk are cleaned as webpack // cleans its output, in standalone mode and in plugin mode alike — with // `writeToDisk: true` webpack does it itself, as the real file system is its -// output file system; with a function, webpack writes to memory and the -// middleware copies to disk, so it cleans the disk too. +// output file system; with a function, webpack writes to memory and to the +// disk, an additional output it cleans too. describe("output.clean with writeToDisk", () => { /** @type {string} */ let directory; @@ -161,12 +174,20 @@ describe("output.clean with writeToDisk", () => { fs.writeFileSync(path.join(directory, file), content); } + /** + * @param {string} file a file in `public` + * @returns {string} its path + */ + function inPublic(file) { + return path.join(directory, "public", file); + } + /** * @param {string} file a file in `public` * @param {string=} content its new content, or none to remove it */ function changePublic(file, content) { - const target = path.join(directory, "public", file); + const target = inPublic(file); if (typeof content === "string") { fs.writeFileSync(target, content); @@ -176,7 +197,7 @@ describe("output.clean with writeToDisk", () => { } /** - * Create `public`, for copy-webpack-plugin to copy to the output. + * Create `public`, for copy-webpack-plugin or `output.copy` to copy to the output. */ function createPublic() { fs.mkdirSync(path.join(directory, "public", "images"), { recursive: true }); @@ -184,6 +205,18 @@ describe("output.clean with writeToDisk", () => { changePublic("images/logo.svg", ""); } + const copiers = [ + [ + "copy-webpack-plugin", + (patterns) => + createCompiler({ clean: true }, [new CopyPlugin({ patterns })]), + ], + [ + "output.copy", + (patterns) => createCompiler({ clean: true, copy: patterns }), + ], + ]; + const writeToDiskValues = [ ["true", true], ["a function", () => true], @@ -194,267 +227,344 @@ describe("output.clean with writeToDisk", () => { ["plugin", true], ]) { describe(`in ${mode} mode`, () => { - for (const [label, writeToDisk] of writeToDiskValues) { - it(`cleans the disk on the first build and on a rebuild with "writeToDisk" ${label}`, async () => { - const compiler = createCompiler({ clean: true }); - const { instance, close } = start( - compiler, - { writeToDisk }, - isPlugin, - ); - - try { - await built(instance); - - const first = listDist(); - - expect(first).toHaveLength(1); - expect(first[0]).toMatch(/^main\.[0-9a-f]+\.js$/); - - await rebuild(compiler); - - const second = listDist(); - - expect(second).toHaveLength(1); - expect(second[0]).toMatch(/^main\.[0-9a-f]+\.js$/); - expect(second[0]).not.toBe(first[0]); - } finally { - await close(); - } - }); - } - - it('writes to disk, and cleans it, with "writeToDisk" true and an "outputFileSystem" of your own', async () => { + it('cleans the disk on the first build and on a rebuild with "writeToDisk" true, as webpack writes there itself', async () => { const compiler = createCompiler({ clean: true }); const { instance, close } = start( compiler, - { - writeToDisk: true, - outputFileSystem: createFsFromVolume(new Volume()), - }, + { writeToDisk: true }, isPlugin, ); try { await built(instance); - // Before, nothing reached the disk at all: only the stale files. - expect(listDist()).toEqual([ - expect.stringMatching(/^main\.[0-9a-f]+\.js$/), - ]); - } finally { - await close(); - } - }); + const first = listDist(); - it("keeps what `clean.keep` keeps on disk", async () => { - const compiler = createCompiler({ clean: { keep: /\.css$/ } }); - const { instance, close } = start( - compiler, - { writeToDisk: () => true }, - isPlugin, - ); - - try { - await built(instance); - - expect(listDist()).toEqual([ + expect(first).toEqual([ expect.stringMatching(/^main\.[0-9a-f]+\.js$/), - "nested/stale.css", ]); - } finally { - await close(); - } - }); - it("removes nothing from disk with `clean.dry`", async () => { - const compiler = createCompiler({ clean: { dry: true } }); - const { instance, close } = start( - compiler, - { writeToDisk: () => true }, - isPlugin, - ); + await rebuild(compiler); - try { - await built(instance); + const second = listDist(); - expect(listDist()).toEqual([ + expect(second).toEqual([ expect.stringMatching(/^main\.[0-9a-f]+\.js$/), - "nested/stale.css", - "stale.js", ]); + expect(second[0]).not.toBe(first[0]); } finally { await close(); } }); - it("removes nothing from disk without `output.clean`", async () => { - const compiler = createCompiler({}); - const { instance, close } = start( - compiler, - { writeToDisk: () => true }, - isPlugin, - ); - - try { - await built(instance); - await rebuild(compiler); + describeWithoutAdditionalOutputs( + "when webpack has no `additionalOutputs`, as before 5.113.0 and with Rspack", + () => { + it('copies to disk itself, without cleaning it, with "writeToDisk" a function', async () => { + const compiler = createCompiler({ clean: true }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true }, + isPlugin, + ); - // Both builds' bundles, and the earlier session's files. - expect(listDist()).toHaveLength(4); - } finally { - await close(); - } - }); + try { + await built(instance); - it("cleans from disk a chunk named with a query string once it is gone", async () => { - writeSource( - "index.js", - 'import(/* webpackChunkName: "lazy" */ "./lazy.js");', - ); - writeSource("lazy.js", "console.log(1);"); + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + "nested/stale.css", + "stale.js", + ]); + } finally { + await close(); + } + }); + }, + ); + + describeWithAdditionalOutputs( + "when webpack writes to disk as an additional output", + () => { + it('cleans the disk on the first build and on a rebuild with "writeToDisk" a function', async () => { + const writeToDisk = () => true; + const compiler = createCompiler({ clean: true }); + const { instance, close } = start( + compiler, + { writeToDisk }, + isPlugin, + ); - const compiler = createCompiler({ - clean: true, - chunkFilename: "[name].js?[contenthash]", - }); - const { instance, close } = start( - compiler, - { writeToDisk: (targetPath) => targetPath.endsWith(".js") }, - isPlugin, - ); + try { + await built(instance); - try { - await built(instance); + const first = listDist(); - expect(listDist()).toEqual([ - "lazy.js", - expect.stringMatching(/^main\.[0-9a-f]+\.js$/), - ]); + expect(first).toHaveLength(1); + expect(first[0]).toMatch(/^main\.[0-9a-f]+\.js$/); - // The entry no longer imports it, so the chunk is gone. - await rebuild(compiler); + await rebuild(compiler); - expect(listDist()).toEqual([ - expect.stringMatching(/^main\.[0-9a-f]+\.js$/), - ]); - } finally { - await close(); - } - }); + const second = listDist(); - it("writes to disk without cleaning it when the compiler has no `CleanPlugin`, as with Rspack", async () => { - const compiler = createCompiler({ clean: true }); + expect(second).toHaveLength(1); + expect(second[0]).toMatch(/^main\.[0-9a-f]+\.js$/); + expect(second[0]).not.toBe(first[0]); + } finally { + await close(); + } + }); - compiler.webpack = { ...compiler.webpack, CleanPlugin: undefined }; + it('writes to disk, and cleans it, with "writeToDisk" true and an "outputFileSystem" of your own', async () => { + const compiler = createCompiler({ clean: true }); + const { instance, close } = start( + compiler, + { + writeToDisk: true, + outputFileSystem: createFsFromVolume(new Volume()), + }, + isPlugin, + ); - const { instance, close } = start( - compiler, - { writeToDisk: () => true }, - isPlugin, - ); + try { + await built(instance); - try { - await built(instance); + // Before, nothing reached the disk at all: only the stale files. + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + ]); + } finally { + await close(); + } + }); - expect(listDist()).toEqual([ - expect.stringMatching(/^main\.[0-9a-f]+\.js$/), - "nested/stale.css", - "stale.js", - ]); - } finally { - await close(); - } - }); + it("keeps what `clean.keep` keeps on disk", async () => { + const compiler = createCompiler({ clean: { keep: /\.css$/ } }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true }, + isPlugin, + ); - describe("with copy-webpack-plugin", () => { - beforeEach(createPublic); + try { + await built(instance); - /** - * @returns {import("webpack").Compiler} compiler copying `public` to the output - */ - function createCopyingCompiler() { - return createCompiler({ clean: true }, [ - new CopyPlugin({ patterns: [{ from: "public" }] }), - ]); - } + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + "nested/stale.css", + ]); + } finally { + await close(); + } + }); - for (const [label, writeToDisk] of writeToDiskValues) { - it(`writes the copied files to disk and keeps them clean with "writeToDisk" ${label}`, async () => { - const compiler = createCopyingCompiler(); + it("removes nothing from disk with `clean.dry`", async () => { + const compiler = createCompiler({ clean: { dry: true } }); const { instance, close } = start( compiler, - { writeToDisk }, + { writeToDisk: () => true }, isPlugin, ); - const bundle = expect.stringMatching(/^main\.[0-9a-f]+\.js$/); try { await built(instance); - // The copied files beside the bundle, the stale ones gone. expect(listDist()).toEqual([ - "images/logo.svg", - bundle, - "robots.txt", + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + "nested/stale.css", + "stale.js", ]); + } finally { + await close(); + } + }); - // A rebuild of the bundle leaves what is still copied. - const [, firstBundle] = listDist(); + it("removes nothing from disk without `output.clean`", async () => { + const compiler = createCompiler({}); + const { instance, close } = start( + compiler, + { writeToDisk: () => true }, + isPlugin, + ); + try { + await built(instance); await rebuild(compiler); - expect(listDist()).toEqual([ - "images/logo.svg", - bundle, - "robots.txt", - ]); - expect(listDist()[1]).not.toBe(firstBundle); + // Both builds' bundles, and the earlier session's files. + expect(listDist()).toHaveLength(4); + } finally { + await close(); + } + }); - // A changed file is copied again. - await rebuild(compiler, () => changePublic("robots.txt", "v2")); + it("cleans from disk a chunk named with a query string once it is gone", async () => { + writeSource( + "index.js", + 'import(/* webpackChunkName: "lazy" */ "./lazy.js");', + ); + writeSource("lazy.js", "console.log(1);"); - expect(readDist("robots.txt")).toBe("v2"); + const compiler = createCompiler({ + clean: true, + chunkFilename: "[name].js?[contenthash]", + }); + const { instance, close } = start( + compiler, + { writeToDisk: (targetPath) => targetPath.endsWith(".js") }, + isPlugin, + ); - // One no longer copied is cleaned. - await rebuild(compiler, () => changePublic("images/logo.svg")); + try { + await built(instance); - expect(listDist()).toEqual([bundle, "robots.txt"]); + expect(listDist()).toEqual([ + "lazy.js", + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + ]); + + // The entry no longer imports it, so the chunk is gone. + await rebuild(compiler); + + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + ]); } finally { await close(); } }); - } - it("leaves the copied files off disk when the function does not write them", async () => { - // One of them on disk from an earlier session, to be cleaned. - fs.writeFileSync(inDist("robots.txt"), "old"); + for (const [copier, createCopyingCompiler] of copiers) { + describe(`with ${copier}`, () => { + beforeEach(createPublic); + + for (const [label, writeToDisk] of writeToDiskValues) { + it(`writes the copied files to disk and keeps them clean with "writeToDisk" ${label}`, async () => { + const compiler = createCopyingCompiler([{ from: "public" }]); + const { instance, close } = start( + compiler, + { writeToDisk }, + isPlugin, + ); + const bundle = expect.stringMatching(/^main\.[0-9a-f]+\.js$/); + + try { + await built(instance); + + // The copied files beside the bundle, the stale ones gone. + expect(listDist()).toEqual([ + "images/logo.svg", + bundle, + "robots.txt", + ]); + + // A rebuild of the bundle leaves what is still copied. + const [, firstBundle] = listDist(); + + await rebuild(compiler); + + expect(listDist()).toEqual([ + "images/logo.svg", + bundle, + "robots.txt", + ]); + expect(listDist()[1]).not.toBe(firstBundle); + + // A changed file is copied again. + await rebuild(compiler, () => + changePublic("robots.txt", "v2"), + ); + + expect(readDist("robots.txt")).toBe("v2"); + + // One no longer copied is cleaned. + await rebuild(compiler, () => + changePublic("images/logo.svg"), + ); + + expect(listDist()).toEqual([bundle, "robots.txt"]); + } finally { + await close(); + } + }); + } + + it("leaves the copied files off disk when the function does not write them", async () => { + // One of them on disk from an earlier session, to be cleaned. + fs.writeFileSync(inDist("robots.txt"), "old"); + + const compiler = createCopyingCompiler([{ from: "public" }]); + const { instance, close } = start( + compiler, + { writeToDisk: (targetPath) => targetPath.endsWith(".js") }, + isPlugin, + ); + + try { + await built(instance); + + // Served from memory, never written, and the stale files cleaned, the + // earlier copy of one the function skips too. + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + ]); + expect( + instance.context.outputFileSystem + .readFileSync(inDist("robots.txt")) + .toString(), + ).toBe("v1"); + } finally { + await close(); + } + }); + }); + } - const compiler = createCopyingCompiler(); - const { instance, close } = start( - compiler, - { writeToDisk: (targetPath) => targetPath.endsWith(".js") }, - isPlugin, + describeWithLinksAndPermissions( + "with output.copy, links and permissions", + () => { + beforeEach(createPublic); + + it("writes a copied link to disk as a link, and the permissions it keeps", async () => { + fs.chmodSync(inPublic("robots.txt"), 0o755); + fs.symlinkSync("robots.txt", inPublic("link.txt")); + + const compiler = createCompiler({ + clean: true, + copy: [ + { + from: "public", + globOptions: { followSymlinks: false }, + preservePermissions: true, + }, + ], + }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true }, + isPlugin, + ); + + try { + await built(instance); + + expect( + fs.lstatSync(inDist("link.txt")).isSymbolicLink(), + ).toBe(true); + expect(fs.readlinkSync(inDist("link.txt"))).toBe( + "robots.txt", + ); + expect(fs.statSync(inDist("robots.txt")).mode & 0o777).toBe( + 0o755, + ); + } finally { + await close(); + } + }); + }, ); - - try { - await built(instance); - - // Served from memory, never written, and the stale files cleaned, the - // earlier copy of one the function skips too. - expect(listDist()).toEqual([ - expect.stringMatching(/^main\.[0-9a-f]+\.js$/), - ]); - expect( - instance.context.outputFileSystem - .readFileSync(inDist("robots.txt")) - .toString(), - ).toBe("v1"); - } finally { - await close(); - } - }); - }); + }, + ); }); } }); From b38df13c6e1dd3ed7e89d047ea738974467e9342 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:21:40 +0000 Subject: [PATCH 11/18] test: cover the disk added through additionalOutputs on any webpack Give the compiler that hook, so what writeToDisk adds there is checked where the installed webpack has none yet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- test/write-to-disk-clean.test.js | 93 ++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index 5b1c272e2..1fe292064 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -568,3 +568,96 @@ describe("output.clean with writeToDisk", () => { }); } }); + +// What `writeToDisk` adds to a webpack with `additionalOutputs`, checked on any +// webpack by giving the compiler that hook. +describe("writeToDisk with an additionalOutputs hook", () => { + /** + * @returns {import("webpack").Compiler & { hooks: { additionalOutputs: import("tapable").SyncHook<[Set<{ outputFileSystem: unknown, test?: (targetPath: string) => boolean }>]> } }} a compiler having the hook + */ + function createCompilerWithHook() { + const compiler = webpack({ + mode: "development", + entry: "./index.js", + infrastructureLogging: { level: "error" }, + stats: "none", + }); + // A `SyncHook` as webpack has, from the class its own hooks use. + const SyncHook = compiler.hooks.compilation.constructor; + + return Object.create(compiler, { + hooks: { + value: { + ...compiler.hooks, + additionalOutputs: new SyncHook(["outputs"]), + }, + }, + }); + } + + /** + * @param {ReturnType} compiler compiler + * @returns {{ outputFileSystem: unknown, test?: (targetPath: string) => boolean }[]} the outputs added + */ + function collect(compiler) { + const outputs = new Set(); + + compiler.hooks.additionalOutputs.call(outputs); + + return [...outputs]; + } + + it("adds the disk as an additional output, taking what the function takes", async () => { + const compiler = createCompilerWithHook(); + const instance = middleware( + compiler, + { writeToDisk: (targetPath) => targetPath.endsWith(".js") }, + true, + ); + + try { + const [output, ...rest] = collect(compiler); + + expect(rest).toHaveLength(0); + expect(output.outputFileSystem).toBe(fs); + expect(output.test("/dist/main.js")).toBe(true); + expect(output.test("/dist/robots.txt")).toBe(false); + // webpack writes there, so the middleware copies nothing itself. + expect( + compiler.hooks.assetEmitted.taps.filter( + (tap) => tap.name === "DevMiddleware", + ), + ).toHaveLength(0); + } finally { + await new Promise((resolve) => { + instance.close(resolve); + }); + } + }); + + it('adds the disk taking every asset with "writeToDisk" true and an "outputFileSystem" of your own, once for the compiler', async () => { + const compiler = createCompilerWithHook(); + const options = { + writeToDisk: true, + outputFileSystem: createFsFromVolume(new Volume()), + }; + const first = middleware(compiler, options, true); + const second = middleware(compiler, options, true); + + try { + const outputs = collect(compiler); + + expect(outputs).toHaveLength(1); + expect(outputs[0].test("/dist/robots.txt")).toBe(true); + } finally { + await Promise.all( + [first, second].map( + (instance) => + new Promise((resolve) => { + instance.close(resolve); + }), + ), + ); + } + }); +}); From 9dd4ab05627ac5c1c3a3da6daf9b9c337900a3d8 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:36:23 +0000 Subject: [PATCH 12/18] fix: clean writeToDisk files through a two-way output file system Replace the webpack hook with a file system given to the compiler that writes to memory and, for the paths `writeToDisk` takes, to disk, removes files from both and lists both, so `output.clean` cleans the disk on every webpack 5 version and on Rspack. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- .changeset/write-to-disk-output-clean.md | 2 +- README.md | 2 +- src/index.js | 381 ++++++++++---- test/write-to-disk-clean.test.js | 618 +++++++++-------------- 4 files changed, 518 insertions(+), 485 deletions(-) diff --git a/.changeset/write-to-disk-output-clean.md b/.changeset/write-to-disk-output-clean.md index d19d6e6ab..1e9791373 100644 --- a/.changeset/write-to-disk-output-clean.md +++ b/.changeset/write-to-disk-output-clean.md @@ -2,4 +2,4 @@ "webpack-dev-middleware": patch --- -Clean the files `writeToDisk` writes when `output.clean` is set and `writeToDisk` is a function. webpack wrote the build to memory and cleaned only that, so the copies on disk were never cleaned: the previous session's files stayed, and every rebuild left another `main.[contenthash].js` behind. With webpack 5.113.0 or later the middleware adds the disk as an additional output (`compiler.hooks.additionalOutputs`), so webpack writes the files there itself, links, permissions and times included, and `output.clean` cleans the disk too, honoring `clean.keep` and `clean.dry`, in plugin mode as in standalone mode; with an older webpack or Rspack the middleware copies to disk as before. `writeToDisk: true` with an `outputFileSystem` of your own now writes to disk too: it wrote nothing there before. +Clean the files `writeToDisk` writes when `output.clean` is set. webpack wrote the build to memory and cleaned only that, so the copies on disk were never cleaned: the previous session's files stayed, and every rebuild left another `main.[contenthash].js` behind. The middleware now gives webpack a file system that writes to memory and, for the files `writeToDisk` takes, to disk, and that removes and lists files on both, so `output.clean` cleans the disk too, honoring `clean.keep` and `clean.dry`, in plugin mode as in standalone mode, with every webpack 5 version and with Rspack. `writeToDisk: true` with an `outputFileSystem` of your own now writes to disk too: it wrote nothing there before. diff --git a/README.md b/README.md index 0d2a31c0c..ef2764295 100644 --- a/README.md +++ b/README.md @@ -293,7 +293,7 @@ middleware(compiler, { }); ``` -With either value, [`output.clean`](https://webpack.js.org/configuration/output/#outputclean) cleans the files on disk as it cleans webpack's output: the directory on the first build, the files a rebuild no longer emits after that, with `clean.keep` and `clean.dry` honored. With a function, webpack writes the files it takes to disk as it writes its own output, links, permissions and times included, which needs webpack 5.113.0 or later; with an older webpack or Rspack the middleware copies them to disk itself, and they are not cleaned. +With either value, [`output.clean`](https://webpack.js.org/configuration/output/#outputclean) cleans the files on disk as it cleans webpack's output: the directory on the first build, the files a rebuild no longer emits after that, with `clean.keep` and `clean.dry` honored. The files the function leaves out stay off disk, and a copy of one left there by an earlier session is removed. Links, permissions and times are written to disk as webpack writes them. This works with every webpack 5 version and with Rspack. An asset named with a query string, such as `[name].js?[contenthash]`, is left on disk once it is gone, as it is without the middleware, until webpack's `output.clean` matches such a name to its file. ### outputFileSystem diff --git a/src/index.js b/src/index.js index c64954413..6e6722bc5 100644 --- a/src/index.js +++ b/src/index.js @@ -522,116 +522,291 @@ function printStats(stats, context) { const PLUGIN_NAME = "DevMiddleware"; /** + * The output file system webpack is given when `writeToDisk` writes to disk + * besides the file system files are served from. It writes to that one, and + * to disk the files `writeToDisk` takes, links, permissions and times + * included. Deletes reach both, and listings and `lstat` see the disk too, + * so webpack's own `output.clean` cleans the disk as it cleans its output: + * stale files from an earlier session, files a rebuild no longer emits, + * `clean.keep` and `clean.dry`. What webpack reads to decide whether to + * write a file comes from the served file system alone. A file `writeToDisk` + * leaves out is removed from disk when written, as `output.clean` would. * @template {IncomingMessage} Request * @template {ServerResponse} Response - * @param {Compiler} compiler compiler + * @param {OutputFileSystem} outputFileSystem the file system files are served from * @param {WithOptional, "watching" | "outputFileSystem">} context context + * @param {Compiler[]} compilers the compilers given this file system + * @returns {OutputFileSystem} the file system writing to both */ -function hookForWriteToDisk(compiler, context) { - compiler.hooks.emit.tap(PLUGIN_NAME, () => { - // @ts-expect-error - if (compiler.hasWebpackDevMiddlewareAssetEmittedCallback) { - return; - } +function createDiskWritingFileSystem(outputFileSystem, context, compilers) { + /** + * @param {string} targetPath absolute path of a file + * @returns {boolean} true when it is written to disk + */ + const takes = (targetPath) => { + const { writeToDisk } = context.options; - compiler.hooks.assetEmitted.tapAsync( - PLUGIN_NAME, - (file, info, callback) => { - const { targetPath, content } = info; - const { writeToDisk: filter } = context.options; - const allowWrite = - filter && typeof filter === "function" ? filter(targetPath) : true; + return typeof writeToDisk === "function" ? writeToDisk(targetPath) : true; + }; - if (!allowWrite) { - return callback(); - } + /** + * Whether `output.clean` would remove a file at this path, left on disk by an + * earlier session. The `keep` hook of `CleanPlugin` is not consulted here. + * @param {string} targetPath absolute path of a file + * @returns {boolean} true when it is cleaned + */ + const isCleaned = (targetPath) => + compilers.some(({ options, outputPath }) => { + const { clean } = options.output; - const dir = path.dirname(targetPath); - const name = compiler.options.name - ? `Child "${compiler.options.name}": ` - : ""; + if (!clean || (typeof clean === "object" && clean.dry)) { + return false; + } - return fs.mkdir(dir, { recursive: true }, (mkdirError) => { - if (mkdirError) { - context.logger.error( - `${name}Unable to write "${dir}" directory to disk:\n${mkdirError}`, - ); + const relativePath = path.relative(outputPath, targetPath); - return callback(mkdirError); - } + if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) { + return false; + } - return fs.writeFile(targetPath, content, (writeFileError) => { - if (writeFileError) { - context.logger.error( - `${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError}`, - ); + const keep = typeof clean === "object" ? clean.keep : undefined; + const file = relativePath.replaceAll("\\", "/"); - return callback(writeFileError); - } + if (keep === undefined) { + return true; + } - context.logger.log(`${name}Asset written to disk: "${targetPath}"`); + if (typeof keep === "string") { + return !file.startsWith(keep); + } - return callback(); - }); - }); - }, - ); + if (keep instanceof RegExp) { + return !keep.test(file); + } - // @ts-expect-error - compiler.hasWebpackDevMiddlewareAssetEmittedCallback = true; - }); -} + if (typeof keep === "function") { + return !keep(file); + } -/** - * Has webpack write to the real disk what `writeToDisk` takes, besides its - * own output file system, where webpack supports more outputs: it then writes - * links, permissions and times there as it does to its own, and `output.clean` - * cleans the disk too. Rspack and webpack before 5.113.0 have no such hook, so - * there the middleware copies to disk itself, which is never cleaned. - * @template {IncomingMessage} Request - * @template {ServerResponse} Response - * @param {Compiler} compiler compiler - * @param {WithOptional, "watching" | "outputFileSystem">} context context - * @returns {boolean} true when webpack writes to disk, otherwise false - */ -function addDiskOutput(compiler, context) { - const { additionalOutputs } = - /** @type {Compiler["hooks"] & { additionalOutputs?: import("tapable").SyncHook<[Set<{ outputFileSystem: OutputFileSystem, test?: (targetPath: string) => boolean }>]> }} */ ( - compiler.hooks - ); + return false; + }); - if (!additionalOutputs) { - return false; - } + /** + * Run a write on disk once it succeeded on the served file system. + * @param {string} targetPath absolute path of the file + * @param {(callback: (err?: NodeJS.ErrnoException | null) => void) => void} write the write on disk + * @param {(err?: NodeJS.ErrnoException | null) => void} callback callback + * @returns {(err?: NodeJS.ErrnoException | null) => void} the callback of the write on the served file system + */ + const thenOnDisk = (targetPath, write, callback) => (err) => { + if (err) { + return callback(err); + } - // @ts-expect-error - if (compiler.hasWebpackDevMiddlewareDiskOutput) { - return true; - } + if (!takes(targetPath)) { + // A copy an earlier session wrote, which `output.clean` counts as current. + if (isCleaned(targetPath)) { + return fs.unlink(targetPath, () => callback()); + } + + return callback(); + } + + const dir = path.dirname(targetPath); + + fs.mkdir(dir, { recursive: true }, (mkdirError) => { + if (mkdirError) { + context.logger.error( + `Unable to write "${dir}" directory to disk:\n${mkdirError}`, + ); + + return callback(mkdirError); + } + + write((writeError) => { + if (writeError) { + context.logger.error( + `Unable to write "${targetPath}" asset to disk:\n${writeError}`, + ); - const output = { - outputFileSystem: /** @type {OutputFileSystem} */ ( - /** @type {unknown} */ (fs) - ), + return callback(writeError); + } + + context.logger.log(`Asset written to disk: "${targetPath}"`); + + return callback(); + }); + }); + }; + + /** + * Remove from both, done once removed from either. + * @param {"unlink" | "rmdir"} method the removal + * @param {string} targetPath absolute path + * @param {(err?: NodeJS.ErrnoException | null) => void} callback callback + */ + const removeFromBoth = (method, targetPath, callback) => { + let pending = 2; + let removed = false; + /** @type {NodeJS.ErrnoException | null | undefined} */ + let firstError; /** - * @param {string} targetPath absolute path of the asset - * @returns {boolean} true when the asset is written to disk + * @param {NodeJS.ErrnoException | null=} err err */ - test: (targetPath) => { - const { writeToDisk: filter } = context.options; + const done = (err) => { + if (!err) { + removed = true; + } else if (!firstError) { + firstError = err; + } - return typeof filter === "function" ? filter(targetPath) : true; - }, + pending -= 1; + + if (pending === 0) { + callback(removed ? null : firstError); + } + }; + + /** @type {EXPECTED_ANY} */ (outputFileSystem)[method](targetPath, done); + fs[method](targetPath, done); }; - additionalOutputs.tap(PLUGIN_NAME, (outputs) => { - outputs.add(output); - }); + /** @type {EXPECTED_ANY} */ + const served = outputFileSystem; + + // What is not written here, such as `readFile`, `stat` and `mkdir`, reaches the served file system alone. + return /** @type {OutputFileSystem} */ ( + Object.create(outputFileSystem, { + writeFile: { + value: ( + /** @type {string} */ targetPath, + /** @type {Buffer} */ content, + /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, + ) => + served.writeFile( + targetPath, + content, + thenOnDisk( + targetPath, + (done) => fs.writeFile(targetPath, content, done), + callback, + ), + ), + }, + symlink: { + value: ( + /** @type {string} */ target, + /** @type {string} */ targetPath, + /** @type {"file" | "dir" | "junction"} */ type, + /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, + ) => + served.symlink( + target, + targetPath, + type, + thenOnDisk( + targetPath, + (done) => + fs.unlink(targetPath, () => + fs.symlink(target, targetPath, type, done), + ), + callback, + ), + ), + }, + chmod: { + value: ( + /** @type {string} */ targetPath, + /** @type {number} */ mode, + /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, + ) => + served.chmod( + targetPath, + mode, + thenOnDisk( + targetPath, + (done) => fs.chmod(targetPath, mode, done), + callback, + ), + ), + }, + utimes: { + value: ( + /** @type {string} */ targetPath, + /** @type {Date} */ atime, + /** @type {Date} */ mtime, + /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, + ) => + served.utimes( + targetPath, + atime, + mtime, + thenOnDisk( + targetPath, + (done) => fs.utimes(targetPath, atime, mtime, done), + callback, + ), + ), + }, + unlink: { + value: ( + /** @type {string} */ targetPath, + /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, + ) => removeFromBoth("unlink", targetPath, callback), + }, + rmdir: { + value: ( + /** @type {string} */ targetPath, + /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, + ) => removeFromBoth("rmdir", targetPath, callback), + }, + // How `output.clean` finds what is on disk alone, left from an earlier session. + lstat: { + value: ( + /** @type {string} */ targetPath, + /** @type {(err: NodeJS.ErrnoException | null, stats?: import("fs").Stats) => void} */ callback, + ) => + served.lstat( + targetPath, + ( + /** @type {NodeJS.ErrnoException | null} */ err, + /** @type {import("fs").Stats} */ stats, + ) => { + if (err && err.code === "ENOENT") { + return fs.lstat(targetPath, callback); + } - // @ts-expect-error - compiler.hasWebpackDevMiddlewareDiskOutput = true; + callback(err, stats); + }, + ), + }, + readdir: { + value: ( + /** @type {string} */ targetPath, + /** @type {(err: NodeJS.ErrnoException | null, entries?: string[]) => void} */ callback, + ) => + served.readdir( + targetPath, + ( + /** @type {NodeJS.ErrnoException | null} */ servedError, + /** @type {string[] | undefined} */ servedEntries, + ) => + fs.readdir(targetPath, (diskError, diskEntries) => { + if (servedError && diskError) { + return callback(servedError); + } - return true; + callback(null, [ + ...new Set([ + ...(servedEntries || []), + ...(diskEntries || []), + ]), + ]); + }), + ), + }, + }) + ); } // TODO in the next major release remove the standalone mode, where the @@ -753,25 +928,6 @@ function wdm(compiler, options = {}, isPlugin = false) { ); } - // Written to disk besides webpack's own output file system: always for a - // function, which filters what is written, and for `true` when an - // `outputFileSystem` of your own is webpack's, as it then stays — before, - // `writeToDisk: true` with one wrote nothing to disk at all. - // TODO in the next major release require a webpack with `additionalOutputs` - // and drop `hookForWriteToDisk`, the copy to disk for those without it. - if ( - typeof options.writeToDisk === "function" || - (options.writeToDisk === true && - options.outputFileSystem && - options.outputFileSystem !== fs) - ) { - for (const compiler of compilersToModify) { - if (!addDiskOutput(compiler, context)) { - hookForWriteToDisk(compiler, context); - } - } - } - // Modify output file system /** @type {OutputFileSystem} */ let outputFileSystem; @@ -799,8 +955,23 @@ function wdm(compiler, options = {}, isPlugin = false) { context.outputFileSystem = outputFileSystem; + // Written to disk besides the served file system: always for a function, + // which filters what is written, and for `true` when an `outputFileSystem` + // of your own stays webpack's — before, `true` with one wrote nothing there. + const compilerOutputFileSystem = + typeof options.writeToDisk === "function" || + (options.writeToDisk === true && + options.outputFileSystem && + options.outputFileSystem !== fs) + ? createDiskWritingFileSystem( + outputFileSystem, + context, + compilersToModify, + ) + : outputFileSystem; + for (const compiler of compilersToModify) { - compiler.outputFileSystem = outputFileSystem; + compiler.outputFileSystem = compilerOutputFileSystem; } // Start watching, but only for standalone usage, for plugin usage stats will be printed by external code, for example - webpack-cli diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index 1fe292064..4183c84ba 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -10,15 +10,6 @@ import middleware from "../src"; jest.spyOn(globalThis.console, "log").mockImplementation(); -// Where webpack writes to more outputs than its own, `writeToDisk` adds the -// real disk as one, and `output.clean` cleans it as webpack's own output. -const hasAdditionalOutputs = "additionalOutputs" in webpack({}).hooks; -const describeWithAdditionalOutputs = hasAdditionalOutputs - ? describe - : describe.skip; -const describeWithoutAdditionalOutputs = hasAdditionalOutputs - ? describe.skip - : describe; // Links and permissions need privileges or mean nothing on Windows. const describeWithLinksAndPermissions = os.platform() === "win32" ? describe.skip : describe; @@ -26,8 +17,8 @@ const describeWithLinksAndPermissions = // `output.clean` with `writeToDisk`: the files on disk are cleaned as webpack // cleans its output, in standalone mode and in plugin mode alike — with // `writeToDisk: true` webpack does it itself, as the real file system is its -// output file system; with a function, webpack writes to memory and to the -// disk, an additional output it cleans too. +// output file system; with a function, webpack writes through a file system +// writing to memory and to disk, and cleans both. describe("output.clean with writeToDisk", () => { /** @type {string} */ let directory; @@ -257,407 +248,278 @@ describe("output.clean with writeToDisk", () => { } }); - describeWithoutAdditionalOutputs( - "when webpack has no `additionalOutputs`, as before 5.113.0 and with Rspack", - () => { - it('copies to disk itself, without cleaning it, with "writeToDisk" a function', async () => { - const compiler = createCompiler({ clean: true }); - const { instance, close } = start( - compiler, - { writeToDisk: () => true }, - isPlugin, - ); - - try { - await built(instance); - - expect(listDist()).toEqual([ - expect.stringMatching(/^main\.[0-9a-f]+\.js$/), - "nested/stale.css", - "stale.js", - ]); - } finally { - await close(); - } - }); - }, - ); - - describeWithAdditionalOutputs( - "when webpack writes to disk as an additional output", - () => { - it('cleans the disk on the first build and on a rebuild with "writeToDisk" a function', async () => { - const writeToDisk = () => true; - const compiler = createCompiler({ clean: true }); - const { instance, close } = start( - compiler, - { writeToDisk }, - isPlugin, - ); - - try { - await built(instance); - - const first = listDist(); - - expect(first).toHaveLength(1); - expect(first[0]).toMatch(/^main\.[0-9a-f]+\.js$/); - - await rebuild(compiler); - - const second = listDist(); - - expect(second).toHaveLength(1); - expect(second[0]).toMatch(/^main\.[0-9a-f]+\.js$/); - expect(second[0]).not.toBe(first[0]); - } finally { - await close(); - } - }); + describe("when writing to disk besides the served file system", () => { + it('cleans the disk on the first build and on a rebuild with "writeToDisk" a function', async () => { + const writeToDisk = () => true; + const compiler = createCompiler({ clean: true }); + const { instance, close } = start( + compiler, + { writeToDisk }, + isPlugin, + ); - it('writes to disk, and cleans it, with "writeToDisk" true and an "outputFileSystem" of your own', async () => { - const compiler = createCompiler({ clean: true }); - const { instance, close } = start( - compiler, - { - writeToDisk: true, - outputFileSystem: createFsFromVolume(new Volume()), - }, - isPlugin, - ); - - try { - await built(instance); - - // Before, nothing reached the disk at all: only the stale files. - expect(listDist()).toEqual([ - expect.stringMatching(/^main\.[0-9a-f]+\.js$/), - ]); - } finally { - await close(); - } - }); + try { + await built(instance); - it("keeps what `clean.keep` keeps on disk", async () => { - const compiler = createCompiler({ clean: { keep: /\.css$/ } }); - const { instance, close } = start( - compiler, - { writeToDisk: () => true }, - isPlugin, - ); - - try { - await built(instance); - - expect(listDist()).toEqual([ - expect.stringMatching(/^main\.[0-9a-f]+\.js$/), - "nested/stale.css", - ]); - } finally { - await close(); - } - }); + const first = listDist(); - it("removes nothing from disk with `clean.dry`", async () => { - const compiler = createCompiler({ clean: { dry: true } }); - const { instance, close } = start( - compiler, - { writeToDisk: () => true }, - isPlugin, - ); - - try { - await built(instance); - - expect(listDist()).toEqual([ - expect.stringMatching(/^main\.[0-9a-f]+\.js$/), - "nested/stale.css", - "stale.js", - ]); - } finally { - await close(); - } - }); + expect(first).toHaveLength(1); + expect(first[0]).toMatch(/^main\.[0-9a-f]+\.js$/); - it("removes nothing from disk without `output.clean`", async () => { - const compiler = createCompiler({}); - const { instance, close } = start( - compiler, - { writeToDisk: () => true }, - isPlugin, - ); - - try { - await built(instance); - await rebuild(compiler); - - // Both builds' bundles, and the earlier session's files. - expect(listDist()).toHaveLength(4); - } finally { - await close(); - } - }); + await rebuild(compiler); - it("cleans from disk a chunk named with a query string once it is gone", async () => { - writeSource( - "index.js", - 'import(/* webpackChunkName: "lazy" */ "./lazy.js");', - ); - writeSource("lazy.js", "console.log(1);"); + const second = listDist(); - const compiler = createCompiler({ - clean: true, - chunkFilename: "[name].js?[contenthash]", - }); - const { instance, close } = start( - compiler, - { writeToDisk: (targetPath) => targetPath.endsWith(".js") }, - isPlugin, - ); - - try { - await built(instance); - - expect(listDist()).toEqual([ - "lazy.js", - expect.stringMatching(/^main\.[0-9a-f]+\.js$/), - ]); - - // The entry no longer imports it, so the chunk is gone. - await rebuild(compiler); - - expect(listDist()).toEqual([ - expect.stringMatching(/^main\.[0-9a-f]+\.js$/), - ]); - } finally { - await close(); - } + expect(second).toHaveLength(1); + expect(second[0]).toMatch(/^main\.[0-9a-f]+\.js$/); + expect(second[0]).not.toBe(first[0]); + } finally { + await close(); + } + }); + + it('writes to disk, and cleans it, with "writeToDisk" true and an "outputFileSystem" of your own', async () => { + const compiler = createCompiler({ clean: true }); + const { instance, close } = start( + compiler, + { + writeToDisk: true, + outputFileSystem: createFsFromVolume(new Volume()), + }, + isPlugin, + ); + + try { + await built(instance); + + // Before, nothing reached the disk at all: only the stale files. + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + ]); + } finally { + await close(); + } + }); + + it("keeps what `clean.keep` keeps on disk", async () => { + const compiler = createCompiler({ clean: { keep: /\.css$/ } }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true }, + isPlugin, + ); + + try { + await built(instance); + + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + "nested/stale.css", + ]); + } finally { + await close(); + } + }); + + it("removes nothing from disk with `clean.dry`", async () => { + const compiler = createCompiler({ clean: { dry: true } }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true }, + isPlugin, + ); + + try { + await built(instance); + + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + "nested/stale.css", + "stale.js", + ]); + } finally { + await close(); + } + }); + + it("removes nothing from disk without `output.clean`", async () => { + const compiler = createCompiler({}); + const { instance, close } = start( + compiler, + { writeToDisk: () => true }, + isPlugin, + ); + + try { + await built(instance); + await rebuild(compiler); + + // Both builds' bundles, and the earlier session's files. + expect(listDist()).toHaveLength(4); + } finally { + await close(); + } + }); + + it("writes to disk a chunk named with a query string under its file name", async () => { + writeSource( + "index.js", + 'import(/* webpackChunkName: "lazy" */ "./lazy.js");', + ); + writeSource("lazy.js", "console.log(1);"); + + const compiler = createCompiler({ + clean: true, + chunkFilename: "[name].js?[contenthash]", }); + const { instance, close } = start( + compiler, + { writeToDisk: (targetPath) => targetPath.endsWith(".js") }, + isPlugin, + ); - for (const [copier, createCopyingCompiler] of copiers) { - describe(`with ${copier}`, () => { - beforeEach(createPublic); - - for (const [label, writeToDisk] of writeToDiskValues) { - it(`writes the copied files to disk and keeps them clean with "writeToDisk" ${label}`, async () => { - const compiler = createCopyingCompiler([{ from: "public" }]); - const { instance, close } = start( - compiler, - { writeToDisk }, - isPlugin, - ); - const bundle = expect.stringMatching(/^main\.[0-9a-f]+\.js$/); - - try { - await built(instance); - - // The copied files beside the bundle, the stale ones gone. - expect(listDist()).toEqual([ - "images/logo.svg", - bundle, - "robots.txt", - ]); - - // A rebuild of the bundle leaves what is still copied. - const [, firstBundle] = listDist(); - - await rebuild(compiler); - - expect(listDist()).toEqual([ - "images/logo.svg", - bundle, - "robots.txt", - ]); - expect(listDist()[1]).not.toBe(firstBundle); - - // A changed file is copied again. - await rebuild(compiler, () => - changePublic("robots.txt", "v2"), - ); - - expect(readDist("robots.txt")).toBe("v2"); - - // One no longer copied is cleaned. - await rebuild(compiler, () => - changePublic("images/logo.svg"), - ); - - expect(listDist()).toEqual([bundle, "robots.txt"]); - } finally { - await close(); - } - }); - } + try { + await built(instance); + + // Cleaning it once it is gone is up to webpack's `output.clean`, + // which has to match such a name to its file. + expect(listDist()).toEqual([ + "lazy.js", + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + ]); + } finally { + await close(); + } + }); - it("leaves the copied files off disk when the function does not write them", async () => { - // One of them on disk from an earlier session, to be cleaned. - fs.writeFileSync(inDist("robots.txt"), "old"); + for (const [copier, createCopyingCompiler] of copiers) { + describe(`with ${copier}`, () => { + beforeEach(createPublic); + for (const [label, writeToDisk] of writeToDiskValues) { + it(`writes the copied files to disk and keeps them clean with "writeToDisk" ${label}`, async () => { const compiler = createCopyingCompiler([{ from: "public" }]); const { instance, close } = start( compiler, - { writeToDisk: (targetPath) => targetPath.endsWith(".js") }, + { writeToDisk }, isPlugin, ); + const bundle = expect.stringMatching(/^main\.[0-9a-f]+\.js$/); try { await built(instance); - // Served from memory, never written, and the stale files cleaned, the - // earlier copy of one the function skips too. + // The copied files beside the bundle, the stale ones gone. expect(listDist()).toEqual([ - expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + "images/logo.svg", + bundle, + "robots.txt", ]); - expect( - instance.context.outputFileSystem - .readFileSync(inDist("robots.txt")) - .toString(), - ).toBe("v1"); - } finally { - await close(); - } - }); - }); - } - describeWithLinksAndPermissions( - "with output.copy, links and permissions", - () => { - beforeEach(createPublic); - - it("writes a copied link to disk as a link, and the permissions it keeps", async () => { - fs.chmodSync(inPublic("robots.txt"), 0o755); - fs.symlinkSync("robots.txt", inPublic("link.txt")); - - const compiler = createCompiler({ - clean: true, - copy: [ - { - from: "public", - globOptions: { followSymlinks: false }, - preservePermissions: true, - }, - ], - }); - const { instance, close } = start( - compiler, - { writeToDisk: () => true }, - isPlugin, - ); + // A rebuild of the bundle leaves what is still copied. + const [, firstBundle] = listDist(); - try { - await built(instance); + await rebuild(compiler); - expect( - fs.lstatSync(inDist("link.txt")).isSymbolicLink(), - ).toBe(true); - expect(fs.readlinkSync(inDist("link.txt"))).toBe( + expect(listDist()).toEqual([ + "images/logo.svg", + bundle, "robots.txt", + ]); + expect(listDist()[1]).not.toBe(firstBundle); + + // A changed file is copied again. + await rebuild(compiler, () => + changePublic("robots.txt", "v2"), ); - expect(fs.statSync(inDist("robots.txt")).mode & 0o777).toBe( - 0o755, + + expect(readDist("robots.txt")).toBe("v2"); + + // One no longer copied is cleaned. + await rebuild(compiler, () => + changePublic("images/logo.svg"), ); + + expect(listDist()).toEqual([bundle, "robots.txt"]); } finally { await close(); } }); - }, - ); - }, - ); - }); - } -}); - -// What `writeToDisk` adds to a webpack with `additionalOutputs`, checked on any -// webpack by giving the compiler that hook. -describe("writeToDisk with an additionalOutputs hook", () => { - /** - * @returns {import("webpack").Compiler & { hooks: { additionalOutputs: import("tapable").SyncHook<[Set<{ outputFileSystem: unknown, test?: (targetPath: string) => boolean }>]> } }} a compiler having the hook - */ - function createCompilerWithHook() { - const compiler = webpack({ - mode: "development", - entry: "./index.js", - infrastructureLogging: { level: "error" }, - stats: "none", - }); - // A `SyncHook` as webpack has, from the class its own hooks use. - const SyncHook = compiler.hooks.compilation.constructor; - - return Object.create(compiler, { - hooks: { - value: { - ...compiler.hooks, - additionalOutputs: new SyncHook(["outputs"]), - }, - }, - }); - } + } - /** - * @param {ReturnType} compiler compiler - * @returns {{ outputFileSystem: unknown, test?: (targetPath: string) => boolean }[]} the outputs added - */ - function collect(compiler) { - const outputs = new Set(); + it("leaves the copied files off disk when the function does not write them", async () => { + // One of them on disk from an earlier session, to be cleaned. + fs.writeFileSync(inDist("robots.txt"), "old"); + + const compiler = createCopyingCompiler([{ from: "public" }]); + const { instance, close } = start( + compiler, + { writeToDisk: (targetPath) => targetPath.endsWith(".js") }, + isPlugin, + ); + + try { + await built(instance); + + // Served from memory, never written, and the stale files cleaned, the + // earlier copy of one the function skips too. + expect(listDist()).toEqual([ + expect.stringMatching(/^main\.[0-9a-f]+\.js$/), + ]); + expect( + instance.context.outputFileSystem + .readFileSync(inDist("robots.txt")) + .toString(), + ).toBe("v1"); + } finally { + await close(); + } + }); + }); + } - compiler.hooks.additionalOutputs.call(outputs); + describeWithLinksAndPermissions( + "with output.copy, links and permissions", + () => { + beforeEach(createPublic); + + it("writes a copied link to disk as a link, and the permissions it keeps", async () => { + fs.chmodSync(inPublic("robots.txt"), 0o755); + fs.symlinkSync("robots.txt", inPublic("link.txt")); + + const compiler = createCompiler({ + clean: true, + copy: [ + { + from: "public", + globOptions: { followSymlinks: false }, + preservePermissions: true, + }, + ], + }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true }, + isPlugin, + ); - return [...outputs]; - } + try { + await built(instance); - it("adds the disk as an additional output, taking what the function takes", async () => { - const compiler = createCompilerWithHook(); - const instance = middleware( - compiler, - { writeToDisk: (targetPath) => targetPath.endsWith(".js") }, - true, - ); - - try { - const [output, ...rest] = collect(compiler); - - expect(rest).toHaveLength(0); - expect(output.outputFileSystem).toBe(fs); - expect(output.test("/dist/main.js")).toBe(true); - expect(output.test("/dist/robots.txt")).toBe(false); - // webpack writes there, so the middleware copies nothing itself. - expect( - compiler.hooks.assetEmitted.taps.filter( - (tap) => tap.name === "DevMiddleware", - ), - ).toHaveLength(0); - } finally { - await new Promise((resolve) => { - instance.close(resolve); + expect(fs.lstatSync(inDist("link.txt")).isSymbolicLink()).toBe( + true, + ); + expect(fs.readlinkSync(inDist("link.txt"))).toBe("robots.txt"); + expect(fs.statSync(inDist("robots.txt")).mode & 0o777).toBe( + 0o755, + ); + } finally { + await close(); + } + }); + }, + ); }); - } - }); - - it('adds the disk taking every asset with "writeToDisk" true and an "outputFileSystem" of your own, once for the compiler', async () => { - const compiler = createCompilerWithHook(); - const options = { - writeToDisk: true, - outputFileSystem: createFsFromVolume(new Volume()), - }; - const first = middleware(compiler, options, true); - const second = middleware(compiler, options, true); - - try { - const outputs = collect(compiler); - - expect(outputs).toHaveLength(1); - expect(outputs[0].test("/dist/robots.txt")).toBe(true); - } finally { - await Promise.all( - [first, second].map( - (instance) => - new Promise((resolve) => { - instance.close(resolve); - }), - ), - ); - } - }); + }); + } }); From 8d364c258e3477f0f9a484ca1bab3f3c02a51d38 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:47:17 +0000 Subject: [PATCH 13/18] test: wait for the rebuild through watchRun instead of startTime A build restarted for a change keeps the startTime it began with, so it could be taken for the build before the change and never awaited. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- test/write-to-disk-clean.test.js | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index 4183c84ba..c06f2348d 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -115,13 +115,17 @@ describe("output.clean with writeToDisk", () => { change = () => fs.writeFileSync(path.join(directory, "index.js"), "console.log(2);"), ) { - /** @type {number} */ - let changedAt = Infinity; - // The build that started after the change: the watcher may run one more - // for the files the test wrote before it started, as on macOS. + let changed = false; + let rebuilding = false; + // The build run after the change: the watcher may run one more for the files + // the test wrote before it started, as on macOS. `watchRun` is called again + // when a build is restarted, which keeps its `startTime`, so that is not used. + compiler.hooks.watchRun.tap("test", () => { + rebuilding = changed; + }); const done = new Promise((resolve) => { - compiler.hooks.done.tap("test", (stats) => { - if (stats.startTime >= changedAt) { + compiler.hooks.done.tap("test", () => { + if (rebuilding) { resolve(); } }); @@ -132,7 +136,7 @@ describe("output.clean with writeToDisk", () => { setTimeout(resolve, 500); }); change(); - changedAt = Date.now(); + changed = true; await done; // The middleware writes to disk as the build emits; let it finish. From 06b38b5ea6b57e1f0099ae16aeda6e16eacb4a30 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:36:29 +0000 Subject: [PATCH 14/18] fix: handle file systems of your own when writing to disk Write to disk with `writeToDisk: true` when the compiler has a file system of its own, not only one given in `outputFileSystem`. Give a file system that is the disk itself, Node.js `fs` or webpack's `graceful-fs`, as it is, so nothing is written or removed twice, and keep the methods webpack does without, such as `symlink`, only where the file system has them. Test both modes with a file system of your own on the compiler and in `outputFileSystem`: what is written, served and cleaned on each side, `clean.keep` and `clean.dry`, one lacking optional methods, and a multi-compiler. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- .changeset/write-to-disk-output-clean.md | 2 +- .cspell.json | 3 +- README.md | 2 +- src/index.js | 299 +++++++------ test/write-to-disk-clean.test.js | 523 +++++++++++++++++++++++ 5 files changed, 693 insertions(+), 136 deletions(-) diff --git a/.changeset/write-to-disk-output-clean.md b/.changeset/write-to-disk-output-clean.md index 1e9791373..019e39a0d 100644 --- a/.changeset/write-to-disk-output-clean.md +++ b/.changeset/write-to-disk-output-clean.md @@ -2,4 +2,4 @@ "webpack-dev-middleware": patch --- -Clean the files `writeToDisk` writes when `output.clean` is set. webpack wrote the build to memory and cleaned only that, so the copies on disk were never cleaned: the previous session's files stayed, and every rebuild left another `main.[contenthash].js` behind. The middleware now gives webpack a file system that writes to memory and, for the files `writeToDisk` takes, to disk, and that removes and lists files on both, so `output.clean` cleans the disk too, honoring `clean.keep` and `clean.dry`, in plugin mode as in standalone mode, with every webpack 5 version and with Rspack. `writeToDisk: true` with an `outputFileSystem` of your own now writes to disk too: it wrote nothing there before. +Clean the files `writeToDisk` writes when `output.clean` is set. webpack wrote the build to memory and cleaned only that, so the copies on disk were never cleaned: the previous session's files stayed, and every rebuild left another `main.[contenthash].js` behind. The middleware now gives webpack a file system that writes to memory and, for the files `writeToDisk` takes, to disk, and that removes and lists files on both, so `output.clean` cleans the disk too, honoring `clean.keep` and `clean.dry`, in plugin mode as in standalone mode, with every webpack 5 version and with Rspack. `writeToDisk: true` with a file system of your own, in `outputFileSystem` or on the compiler, now writes to disk too: it wrote nothing there before. diff --git a/.cspell.json b/.cspell.json index 4b3899365..7b0c058e1 100644 --- a/.cspell.json +++ b/.cspell.json @@ -49,7 +49,8 @@ "valuenow", "webworker", "wildcarded", - "Fapp" + "Fapp", + "gracefulify" ], "ignorePaths": [ "CHANGELOG.md", diff --git a/README.md b/README.md index ef2764295..018d010f6 100644 --- a/README.md +++ b/README.md @@ -293,7 +293,7 @@ middleware(compiler, { }); ``` -With either value, [`output.clean`](https://webpack.js.org/configuration/output/#outputclean) cleans the files on disk as it cleans webpack's output: the directory on the first build, the files a rebuild no longer emits after that, with `clean.keep` and `clean.dry` honored. The files the function leaves out stay off disk, and a copy of one left there by an earlier session is removed. Links, permissions and times are written to disk as webpack writes them. This works with every webpack 5 version and with Rspack. An asset named with a query string, such as `[name].js?[contenthash]`, is left on disk once it is gone, as it is without the middleware, until webpack's `output.clean` matches such a name to its file. +With either value, [`output.clean`](https://webpack.js.org/configuration/output/#outputclean) cleans the files on disk as it cleans webpack's output: the directory on the first build, the files a rebuild no longer emits after that, with `clean.keep` and `clean.dry` honored. The files the function leaves out stay off disk, and a copy of one left there by an earlier session is removed. Links, permissions and times are written to disk as webpack writes them. With a file system of your own, given in `outputFileSystem` or set on the compiler, the files are written to it and to disk, and both are cleaned; one lacking methods webpack does without, such as `symlink`, works too. This works with every webpack 5 version and with Rspack. An asset named with a query string, such as `[name].js?[contenthash]`, is left on disk once it is gone, as it is without the middleware, until webpack's `output.clean` matches such a name to its file. ### outputFileSystem diff --git a/src/index.js b/src/index.js index 6e6722bc5..c38656bf0 100644 --- a/src/index.js +++ b/src/index.js @@ -521,6 +521,19 @@ function printStats(stats, context) { const PLUGIN_NAME = "DevMiddleware"; +/** + * Whether a file system is the disk: Node.js `fs`, as Rspack's output file + * system, or `graceful-fs` wrapping it, as webpack's. + * @param {OutputFileSystem} fileSystem a file system + * @returns {boolean} true when it writes to disk + */ +function isDiskFileSystem(fileSystem) { + return ( + /** @type {unknown} */ (fileSystem) === fs || + typeof (/** @type {EXPECTED_ANY} */ (fileSystem).gracefulify) === "function" + ); +} + /** * The output file system webpack is given when `writeToDisk` writes to disk * besides the file system files are served from. It writes to that one, and @@ -639,6 +652,9 @@ function createDiskWritingFileSystem(outputFileSystem, context, compilers) { }); }; + /** @type {EXPECTED_ANY} */ + const served = outputFileSystem; + /** * Remove from both, done once removed from either. * @param {"unlink" | "rmdir"} method the removal @@ -667,145 +683,165 @@ function createDiskWritingFileSystem(outputFileSystem, context, compilers) { } }; - /** @type {EXPECTED_ANY} */ (outputFileSystem)[method](targetPath, done); + if (served[method]) { + served[method](targetPath, done); + } else { + pending -= 1; + } + fs[method](targetPath, done); }; - /** @type {EXPECTED_ANY} */ - const served = outputFileSystem; - - // What is not written here, such as `readFile`, `stat` and `mkdir`, reaches the served file system alone. - return /** @type {OutputFileSystem} */ ( - Object.create(outputFileSystem, { - writeFile: { - value: ( - /** @type {string} */ targetPath, - /** @type {Buffer} */ content, - /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, - ) => - served.writeFile( - targetPath, - content, - thenOnDisk( - targetPath, - (done) => fs.writeFile(targetPath, content, done), - callback, - ), - ), - }, - symlink: { - value: ( - /** @type {string} */ target, - /** @type {string} */ targetPath, - /** @type {"file" | "dir" | "junction"} */ type, - /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, - ) => - served.symlink( - target, + // What is not written here, such as `readFile`, `stat` and `mkdir`, reaches + // the served file system alone. A method webpack can do without, such as + // `symlink`, is kept only where the served file system has it. + /** @type {PropertyDescriptorMap} */ + const methods = { + writeFile: { + value: ( + /** @type {string} */ targetPath, + /** @type {Buffer} */ content, + /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, + ) => + served.writeFile( + targetPath, + content, + thenOnDisk( targetPath, - type, - thenOnDisk( - targetPath, - (done) => - fs.unlink(targetPath, () => - fs.symlink(target, targetPath, type, done), - ), - callback, - ), + (done) => fs.writeFile(targetPath, content, done), + callback, ), + ), + }, + unlink: { + value: ( + /** @type {string} */ targetPath, + /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, + ) => removeFromBoth("unlink", targetPath, callback), + }, + rmdir: { + value: ( + /** @type {string} */ targetPath, + /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, + ) => removeFromBoth("rmdir", targetPath, callback), + }, + // How `output.clean` finds what is on disk alone, left from an earlier session. + lstat: { + value: ( + /** @type {string} */ targetPath, + /** @type {(err: NodeJS.ErrnoException | null, stats?: import("fs").Stats) => void} */ callback, + ) => + (served.lstat || served.stat).call( + served, + targetPath, + ( + /** @type {NodeJS.ErrnoException | null} */ err, + /** @type {import("fs").Stats} */ stats, + ) => { + if (err && err.code === "ENOENT") { + return fs.lstat(targetPath, callback); + } + + callback(err, stats); + }, + ), + }, + readdir: { + value: ( + /** @type {string} */ targetPath, + /** @type {(err: NodeJS.ErrnoException | null, entries?: string[]) => void} */ callback, + ) => { + /** + * @param {NodeJS.ErrnoException | null} servedError error from the served file system + * @param {string[]=} servedEntries entries on the served file system + * @returns {void} + */ + const withDisk = (servedError, servedEntries) => + fs.readdir(targetPath, (diskError, diskEntries) => { + if (servedError && diskError) { + return callback(servedError); + } + + callback(null, [ + ...new Set([...(servedEntries || []), ...(diskEntries || [])]), + ]); + }); + + if (!served.readdir) { + return withDisk(null, []); + } + + served.readdir(targetPath, withDisk); }, - chmod: { - value: ( - /** @type {string} */ targetPath, - /** @type {number} */ mode, - /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, - ) => - served.chmod( + }, + }; + + if (served.symlink) { + methods.symlink = { + value: ( + /** @type {string} */ target, + /** @type {string} */ targetPath, + /** @type {"file" | "dir" | "junction"} */ type, + /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, + ) => + served.symlink( + target, + targetPath, + type, + thenOnDisk( targetPath, - mode, - thenOnDisk( - targetPath, - (done) => fs.chmod(targetPath, mode, done), - callback, - ), + (done) => + fs.unlink(targetPath, () => + fs.symlink(target, targetPath, type, done), + ), + callback, ), - }, - utimes: { - value: ( - /** @type {string} */ targetPath, - /** @type {Date} */ atime, - /** @type {Date} */ mtime, - /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, - ) => - served.utimes( + ), + }; + } + + if (served.chmod) { + methods.chmod = { + value: ( + /** @type {string} */ targetPath, + /** @type {number} */ mode, + /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, + ) => + served.chmod( + targetPath, + mode, + thenOnDisk( targetPath, - atime, - mtime, - thenOnDisk( - targetPath, - (done) => fs.utimes(targetPath, atime, mtime, done), - callback, - ), + (done) => fs.chmod(targetPath, mode, done), + callback, ), - }, - unlink: { - value: ( - /** @type {string} */ targetPath, - /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, - ) => removeFromBoth("unlink", targetPath, callback), - }, - rmdir: { - value: ( - /** @type {string} */ targetPath, - /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, - ) => removeFromBoth("rmdir", targetPath, callback), - }, - // How `output.clean` finds what is on disk alone, left from an earlier session. - lstat: { - value: ( - /** @type {string} */ targetPath, - /** @type {(err: NodeJS.ErrnoException | null, stats?: import("fs").Stats) => void} */ callback, - ) => - served.lstat( - targetPath, - ( - /** @type {NodeJS.ErrnoException | null} */ err, - /** @type {import("fs").Stats} */ stats, - ) => { - if (err && err.code === "ENOENT") { - return fs.lstat(targetPath, callback); - } + ), + }; + } - callback(err, stats); - }, - ), - }, - readdir: { - value: ( - /** @type {string} */ targetPath, - /** @type {(err: NodeJS.ErrnoException | null, entries?: string[]) => void} */ callback, - ) => - served.readdir( + if (served.utimes) { + methods.utimes = { + value: ( + /** @type {string} */ targetPath, + /** @type {Date} */ atime, + /** @type {Date} */ mtime, + /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, + ) => + served.utimes( + targetPath, + atime, + mtime, + thenOnDisk( targetPath, - ( - /** @type {NodeJS.ErrnoException | null} */ servedError, - /** @type {string[] | undefined} */ servedEntries, - ) => - fs.readdir(targetPath, (diskError, diskEntries) => { - if (servedError && diskError) { - return callback(servedError); - } - - callback(null, [ - ...new Set([ - ...(servedEntries || []), - ...(diskEntries || []), - ]), - ]); - }), + (done) => fs.utimes(targetPath, atime, mtime, done), + callback, ), - }, - }) + ), + }; + } + + return /** @type {OutputFileSystem} */ ( + Object.create(outputFileSystem, methods) ); } @@ -955,14 +991,11 @@ function wdm(compiler, options = {}, isPlugin = false) { context.outputFileSystem = outputFileSystem; - // Written to disk besides the served file system: always for a function, - // which filters what is written, and for `true` when an `outputFileSystem` - // of your own stays webpack's — before, `true` with one wrote nothing there. + // Written to disk besides the served file system unless that is the disk + // itself: with `true` and a file system of your own, on the compiler or in + // `outputFileSystem`, nothing was written to disk before. const compilerOutputFileSystem = - typeof options.writeToDisk === "function" || - (options.writeToDisk === true && - options.outputFileSystem && - options.outputFileSystem !== fs) + options.writeToDisk && !isDiskFileSystem(outputFileSystem) ? createDiskWritingFileSystem( outputFileSystem, context, diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index c06f2348d..2efa12b2d 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -4,6 +4,7 @@ import path from "node:path"; import CopyPlugin from "copy-webpack-plugin"; import { Volume, createFsFromVolume } from "memfs"; +import request from "supertest"; import webpack from "webpack"; import middleware from "../src"; @@ -526,4 +527,526 @@ describe("output.clean with writeToDisk", () => { }); }); } + + /** + * @returns {import("memfs").IFs} a file system in memory + */ + function createMemoryFileSystem() { + return createFsFromVolume(new Volume()); + } + + /** + * @param {import("memfs").IFs} memory a file system in memory + * @returns {string[]} the files in `dist` on it, relative to it + */ + function listMemory(memory) { + if (!memory.existsSync(dist)) { + return []; + } + + return /** @type {string[]} */ ( + memory.readdirSync(dist, { recursive: true, encoding: "utf8" }) + ) + .filter((file) => memory.statSync(path.join(dist, file)).isFile()) + .map((file) => file.replaceAll("\\", "/")) + .toSorted(); + } + + /** + * A file system of your own, with only the methods named, as webpack can be + * given one lacking those it does without. + * @param {import("memfs").IFs} memory the file system in memory behind it + * @param {string[]} names the methods it has + * @returns {import("../src").OutputFileSystem} the file system + */ + function withMethods(memory, names) { + /** @type {Record} */ + const fileSystem = { join: path.join, dirname: path.dirname }; + + for (const name of names) { + fileSystem[name] = memory[name].bind(memory); + } + + return /** @type {import("../src").OutputFileSystem} */ (fileSystem); + } + + /** + * @param {import("../src").API} instance middleware + * @returns {import("supertest").Agent} requests to it + */ + function requestTo(instance) { + return request((req, res) => { + instance(req, res, () => { + res.statusCode = 404; + res.end(); + }); + }); + } + + const bundle = expect.stringMatching(/^main\.[0-9a-f]+\.js$/); + + /** + * @param {string[]} names the names of the compilers, each writing to its own directory in `dist` + * @returns {import("webpack").MultiCompiler} a multi-compiler + */ + function createMultiCompiler(names) { + return webpack( + names.map((name) => ({ + name, + mode: "development", + devtool: false, + context: directory, + entry: "./index.js", + output: { + path: path.join(dist, name), + filename: "main.[contenthash].js", + clean: true, + }, + infrastructureLogging: { level: "error" }, + stats: "none", + })), + ); + } + + for (const [mode, isPlugin] of [ + ["standalone", false], + ["plugin", true], + ]) { + describe(`with a file system of your own, in ${mode} mode`, () => { + describe("on the compiler", () => { + it('writes to disk and to it, and cleans both, with "writeToDisk" true', async () => { + const memory = createMemoryFileSystem(); + + memory.mkdirSync(inDist("."), { recursive: true }); + memory.writeFileSync(inDist("stale-in-memory.js"), "old"); + + const compiler = createCompiler({ clean: true }); + + compiler.outputFileSystem = memory; + + const { instance, close } = start( + compiler, + { writeToDisk: true }, + isPlugin, + ); + + try { + await built(instance); + + // Served from it, and the disk written too: before, nothing was. + expect(instance.context.outputFileSystem).toBe(memory); + expect(listDist()).toEqual([bundle]); + expect(listMemory(memory)).toEqual(listDist()); + + const [first] = listDist(); + + await rebuild(compiler); + + expect(listDist()).toEqual([bundle]); + expect(listDist()[0]).not.toBe(first); + expect(listMemory(memory)).toEqual(listDist()); + } finally { + await close(); + } + }); + + it("does not write what was in it alone to disk", async () => { + const memory = createMemoryFileSystem(); + + memory.mkdirSync(inDist("only"), { recursive: true }); + memory.writeFileSync(inDist("only/in-memory.js"), "old"); + + const compiler = createCompiler({ clean: { keep: /in-memory/ } }); + + compiler.outputFileSystem = memory; + + const { instance, close } = start( + compiler, + { writeToDisk: true }, + isPlugin, + ); + + try { + await built(instance); + + expect(listMemory(memory)).toEqual([bundle, "only/in-memory.js"]); + // Kept where it was, not copied to disk; what was on disk is cleaned. + expect(listDist()).toEqual([bundle]); + } finally { + await close(); + } + }); + + it("writes the disk once when it is Node.js `fs`, as Rspack's", async () => { + const compiler = createCompiler({ clean: true }); + + compiler.outputFileSystem = fs; + + const { instance, close } = start( + compiler, + { writeToDisk: true }, + isPlugin, + ); + + try { + await built(instance); + + expect(compiler.outputFileSystem).toBe(fs); + expect(listDist()).toEqual([bundle]); + + const [first] = listDist(); + + await rebuild(compiler); + + expect(listDist()).toEqual([bundle]); + expect(listDist()[0]).not.toBe(first); + } finally { + await close(); + } + }); + + it('keeps the file system of webpack, which is the disk, with "writeToDisk" true', async () => { + const compiler = createCompiler({ clean: true }); + const { outputFileSystem } = compiler; + const { instance, close } = start( + compiler, + { writeToDisk: true }, + isPlugin, + ); + + try { + await built(instance); + + expect(compiler.outputFileSystem).toBe(outputFileSystem); + expect(instance.context.outputFileSystem).toBe(outputFileSystem); + expect(listDist()).toEqual([bundle]); + } finally { + await close(); + } + }); + }); + + describe('in "outputFileSystem"', () => { + for (const [label, writeToDisk] of writeToDiskValues) { + it(`writes to disk and to it, and cleans both, with "writeToDisk" ${label}`, async () => { + const memory = createMemoryFileSystem(); + const compiler = createCompiler({ clean: true }); + const { instance, close } = start( + compiler, + { writeToDisk, outputFileSystem: memory }, + isPlugin, + ); + + try { + await built(instance); + + expect(instance.context.outputFileSystem).toBe(memory); + expect(listDist()).toEqual([bundle]); + expect(listMemory(memory)).toEqual([bundle]); + + const [first] = listDist(); + + // What is on disk is what is served. + expect(readDist(first)).toBe( + memory.readFileSync(inDist(first), "utf8"), + ); + + await rebuild(compiler); + + expect(listDist()).toEqual([bundle]); + expect(listDist()[0]).not.toBe(first); + expect(listMemory(memory)).toEqual(listDist()); + } finally { + await close(); + } + }); + } + + it("cleans what was left in it and what was left on disk, without writing the one to the other", async () => { + const memory = createMemoryFileSystem(); + + memory.mkdirSync(inDist("old"), { recursive: true }); + memory.writeFileSync(inDist("old/stale-in-memory.js"), "old"); + + const compiler = createCompiler({ clean: true }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true, outputFileSystem: memory }, + isPlugin, + ); + + try { + await built(instance); + + expect(listMemory(memory)).toEqual([bundle]); + expect(listDist()).toEqual([bundle]); + // The directories emptied are removed too. + expect(fs.existsSync(inDist("nested"))).toBe(false); + expect(memory.existsSync(inDist("old"))).toBe(false); + } finally { + await close(); + } + }); + + it("writes to disk only what the function takes, and serves the rest from it", async () => { + createPublic(); + + const memory = createMemoryFileSystem(); + const compiler = createCompiler({ + clean: true, + copy: [{ from: "public" }], + }); + const { instance, close } = start( + compiler, + { + writeToDisk: (targetPath) => !targetPath.endsWith(".svg"), + outputFileSystem: memory, + }, + isPlugin, + ); + + try { + await built(instance); + + expect(listDist()).toEqual([bundle, "robots.txt"]); + expect(listMemory(memory)).toEqual([ + "images/logo.svg", + bundle, + "robots.txt", + ]); + + const response = await requestTo(instance).get("/images/logo.svg"); + + expect(response.statusCode).toBe(200); + expect(response.body.toString()).toBe(""); + + await rebuild(compiler, () => changePublic("images/logo.svg")); + + expect(listMemory(memory)).toEqual([bundle, "robots.txt"]); + expect(listDist()).toEqual([bundle, "robots.txt"]); + expect( + (await requestTo(instance).get("/images/logo.svg")).statusCode, + ).toBe(404); + } finally { + await close(); + } + }); + + it("keeps on disk and in it what `clean.keep` keeps", async () => { + const memory = createMemoryFileSystem(); + + memory.mkdirSync(inDist("."), { recursive: true }); + memory.writeFileSync(inDist("kept.css"), "old"); + memory.writeFileSync(inDist("removed.js"), "old"); + + const compiler = createCompiler({ clean: { keep: /\.css$/ } }); + const { instance, close } = start( + compiler, + { writeToDisk: true, outputFileSystem: memory }, + isPlugin, + ); + + try { + await built(instance); + + expect(listDist()).toEqual([bundle, "nested/stale.css"]); + expect(listMemory(memory)).toEqual(["kept.css", bundle]); + } finally { + await close(); + } + }); + + it("removes nothing from disk or from it with `clean.dry`", async () => { + const memory = createMemoryFileSystem(); + + memory.mkdirSync(inDist("."), { recursive: true }); + memory.writeFileSync(inDist("stale-in-memory.js"), "old"); + + const compiler = createCompiler({ clean: { dry: true } }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true, outputFileSystem: memory }, + isPlugin, + ); + + try { + await built(instance); + + expect(listDist()).toEqual([ + bundle, + "nested/stale.css", + "stale.js", + ]); + expect(listMemory(memory)).toEqual([bundle, "stale-in-memory.js"]); + } finally { + await close(); + } + }); + + it("serves and writes to disk the same content after a rebuild", async () => { + const memory = createMemoryFileSystem(); + const compiler = createCompiler({ clean: true }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true, outputFileSystem: memory }, + isPlugin, + ); + + try { + await built(instance); + await rebuild(compiler); + + const [file] = listDist(); + const response = await requestTo(instance).get(`/${file}`); + + expect(response.statusCode).toBe(200); + expect(response.text).toContain("console.log(2)"); + expect(readDist(file)).toBe(response.text); + } finally { + await close(); + } + }); + + for (const [label, getFileSystem] of [ + ["Node.js `fs`", () => fs], + [ + "the file system of webpack", + (compiler) => compiler.outputFileSystem, + ], + ]) { + it(`writes the disk once when it is ${label}`, async () => { + const compiler = createCompiler({ clean: true }); + const outputFileSystem = getFileSystem(compiler); + const { instance, close } = start( + compiler, + { writeToDisk: () => true, outputFileSystem }, + isPlugin, + ); + + try { + await built(instance); + + // Given as it is, so nothing is written or removed twice. + expect(compiler.outputFileSystem).toBe(outputFileSystem); + expect(listDist()).toEqual([bundle]); + + const [first] = listDist(); + + await rebuild(compiler); + + expect(listDist()).toEqual([bundle]); + expect(listDist()[0]).not.toBe(first); + } finally { + await close(); + } + }); + } + + it("writes to disk, and cleans it, with one lacking what webpack does without", async () => { + const memory = createMemoryFileSystem(); + // No `lstat`, `readlink`, `symlink`, `chmod` or `utimes`. + const outputFileSystem = withMethods(memory, [ + "mkdir", + "writeFile", + "stat", + "readFile", + "readdir", + "unlink", + "rmdir", + "statSync", + "readFileSync", + "createReadStream", + ]); + const compiler = createCompiler({ clean: true }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true, outputFileSystem }, + isPlugin, + ); + + try { + await built(instance); + + expect(listDist()).toEqual([bundle]); + expect(listMemory(memory)).toEqual([bundle]); + + const [first] = listDist(); + + await rebuild(compiler); + + expect(listDist()).toEqual([bundle]); + expect(listDist()[0]).not.toBe(first); + expect(listMemory(memory)).toEqual(listDist()); + } finally { + await close(); + } + }); + + it("cleans the disk with one that cannot list or remove files", async () => { + const memory = createMemoryFileSystem(); + const outputFileSystem = withMethods(memory, [ + "mkdir", + "writeFile", + "stat", + "readFile", + ]); + const compiler = createCompiler({ clean: true }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true, outputFileSystem }, + isPlugin, + ); + + try { + await built(instance); + + expect(listDist()).toEqual([bundle]); + + const [first] = listDist(); + + await rebuild(compiler); + + expect(listDist()).toEqual([bundle]); + expect(listDist()[0]).not.toBe(first); + } finally { + await close(); + } + }); + + it("cleans the disk of each compiler of a multi-compiler", async () => { + const memory = createMemoryFileSystem(); + + for (const name of ["a", "b"]) { + fs.mkdirSync(inDist(name), { recursive: true }); + fs.writeFileSync(inDist(`${name}/stale.js`), "old"); + } + + const compiler = createMultiCompiler(["a", "b"]); + const { instance, close } = start( + compiler, + { writeToDisk: () => true, outputFileSystem: memory }, + isPlugin, + ); + + try { + await built(instance); + + const inA = expect.stringMatching(/^a\/main\.[0-9a-f]+\.js$/); + const inB = expect.stringMatching(/^b\/main\.[0-9a-f]+\.js$/); + + // The earlier session's files in `dist` itself are no compiler's. + expect(listDist()).toEqual([ + inA, + inB, + "nested/stale.css", + "stale.js", + ]); + expect(listMemory(memory)).toEqual([inA, inB]); + } finally { + await close(); + } + }); + }); + }); + } }); From 7741ebaa723f1365c852924ce0a54b656f24e674 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:43:21 +0000 Subject: [PATCH 15/18] test: list the in-memory files one directory at a time memfs lists recursively with the full path on Windows, so the files were looked up under the output directory twice. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- test/write-to-disk-clean.test.js | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index 2efa12b2d..5b3186549 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -544,12 +544,29 @@ describe("output.clean with writeToDisk", () => { return []; } - return /** @type {string[]} */ ( - memory.readdirSync(dist, { recursive: true, encoding: "utf8" }) - ) - .filter((file) => memory.statSync(path.join(dist, file)).isFile()) - .map((file) => file.replaceAll("\\", "/")) - .toSorted(); + /** @type {string[]} */ + const files = []; + /** + * @param {string} directory a directory in `dist`, relative to it + */ + const walk = (directory) => { + // One level at a time: memfs lists recursively with the full path on Windows. + for (const name of /** @type {string[]} */ ( + memory.readdirSync(path.join(dist, directory), { encoding: "utf8" }) + )) { + const file = directory ? `${directory}/${name}` : name; + + if (memory.statSync(path.join(dist, file)).isDirectory()) { + walk(file); + } else { + files.push(file); + } + } + }; + + walk(""); + + return files.toSorted(); } /** From 480eafafc60c766d158fdd66933e3f0117fa0dc4 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:12:51 +0000 Subject: [PATCH 16/18] test: cover every path of the file system writing to disk Cover keeping a filtered-out file's earlier copy on disk with each form of `clean.keep` and with `clean.dry`, a multi-compiler where a path is outside one compiler's output, copied file times, and the build failing when the served file system or the disk cannot be written. Say why a glob `clean.keep` keeps such a copy rather than leave that branch unexplained. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- src/index.js | 1 + test/write-to-disk-clean.test.js | 180 ++++++++++++++++++++++++++++++- 2 files changed, 180 insertions(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index c38656bf0..4f555aca5 100644 --- a/src/index.js +++ b/src/index.js @@ -601,6 +601,7 @@ function createDiskWritingFileSystem(outputFileSystem, context, compilers) { return !keep(file); } + // A glob condition is not matched here, so what it might keep is kept. return false; }); diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index 5b3186549..6e026c619 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -600,13 +600,24 @@ describe("output.clean with writeToDisk", () => { }); } + /** + * @param {import("webpack").Compiler} compiler compiler + * @returns {Promise} the error a build fails with, as a failed emit does + */ + function failure(compiler) { + return new Promise((resolve) => { + compiler.hooks.failed.tap("test", resolve); + }); + } + const bundle = expect.stringMatching(/^main\.[0-9a-f]+\.js$/); /** * @param {string[]} names the names of the compilers, each writing to its own directory in `dist` + * @param {import("webpack").Configuration["output"]=} output output options * @returns {import("webpack").MultiCompiler} a multi-compiler */ - function createMultiCompiler(names) { + function createMultiCompiler(names, output = {}) { return webpack( names.map((name) => ({ name, @@ -618,6 +629,7 @@ describe("output.clean with writeToDisk", () => { path: path.join(dist, name), filename: "main.[contenthash].js", clean: true, + ...output, }, infrastructureLogging: { level: "error" }, stats: "none", @@ -1030,6 +1042,172 @@ describe("output.clean with writeToDisk", () => { } }); + for (const [label, clean] of [ + ["`clean.keep` a string", { keep: "robots" }], + ["`clean.keep` a RegExp", { keep: /^robots/ }], + [ + "`clean.keep` a function", + { keep: (file) => file === "robots.txt" }, + ], + ["`clean.keep` a glob", { keep: { glob: "robots.*" } }], + ["`clean.dry`", { dry: true }], + ]) { + it(`keeps the copy on disk of a file the function leaves out with ${label}`, async () => { + createPublic(); + fs.writeFileSync(inDist("robots.txt"), "old"); + + const memory = createMemoryFileSystem(); + const compiler = createCompiler({ + clean, + copy: [{ from: "public" }], + }); + const { instance, close } = start( + compiler, + { + writeToDisk: (targetPath) => targetPath.endsWith(".js"), + outputFileSystem: memory, + }, + isPlugin, + ); + + try { + await built(instance); + + expect(readDist("robots.txt")).toBe("old"); + expect(memory.readFileSync(inDist("robots.txt"), "utf8")).toBe( + "v1", + ); + } finally { + await close(); + } + }); + } + + it("removes from disk the copies of what the function leaves out, for each compiler of a multi-compiler", async () => { + for (const name of ["a", "b"]) { + fs.mkdirSync(inDist(name), { recursive: true }); + fs.writeFileSync(inDist(`${name}/main.js`), "old"); + } + + const memory = createMemoryFileSystem(); + const compiler = createMultiCompiler(["a", "b"], { + filename: "main.js", + }); + const { instance, close } = start( + compiler, + { writeToDisk: () => false, outputFileSystem: memory }, + isPlugin, + ); + + try { + await built(instance); + + expect(listDist()).toEqual(["nested/stale.css", "stale.js"]); + expect(listMemory(memory)).toEqual(["a/main.js", "b/main.js"]); + } finally { + await close(); + } + }); + + it("keeps the times of a copied file on disk", async () => { + createPublic(); + + const time = new Date("2020-01-01T00:00:00Z"); + + fs.utimesSync(inPublic("robots.txt"), time, time); + + const memory = createMemoryFileSystem(); + const compiler = createCompiler({ + clean: true, + copy: [{ from: "public", preserveTimestamps: true }], + }); + const { instance, close } = start( + compiler, + { writeToDisk: () => true, outputFileSystem: memory }, + isPlugin, + ); + + try { + await built(instance); + + expect(fs.statSync(inDist("robots.txt")).mtime).toEqual(time); + expect(memory.statSync(inDist("robots.txt")).mtime).toEqual(time); + } finally { + await close(); + } + }); + + it("fails the build, writing nothing to disk, when it cannot write a file", async () => { + const memory = createMemoryFileSystem(); + const outputFileSystem = Object.create(memory, { + writeFile: { + value: (file, content, callback) => + callback(new Error(`Unable to write "${file}"`)), + }, + }); + const compiler = createCompiler({ clean: true }); + const failed = failure(compiler); + const { close } = start( + compiler, + { writeToDisk: () => true, outputFileSystem }, + isPlugin, + ); + + try { + expect((await failed).message).toMatch(/Unable to write ".+main\./); + expect(listDist()).toEqual([]); + } finally { + await close(); + } + }); + + it("fails the build when it cannot create a directory on disk", async () => { + fs.writeFileSync(inDist("blocked"), "a file"); + + const memory = createMemoryFileSystem(); + const compiler = createCompiler({ + clean: true, + path: inDist("blocked/out"), + }); + const failed = failure(compiler); + const { close } = start( + compiler, + { writeToDisk: () => true, outputFileSystem: memory }, + isPlugin, + ); + + try { + expect((await failed).code).toMatch(/^E/); + expect(readDist("blocked")).toBe("a file"); + } finally { + await close(); + } + }); + + it("fails the build when it cannot write a file to disk", async () => { + // A directory where the bundle goes. + fs.mkdirSync(inDist("main.js")); + + const memory = createMemoryFileSystem(); + const compiler = createCompiler({ + clean: { keep: "main.js" }, + filename: "main.js", + }); + const failed = failure(compiler); + const { close } = start( + compiler, + { writeToDisk: () => true, outputFileSystem: memory }, + isPlugin, + ); + + try { + expect((await failed).code).toMatch(/^E/); + expect(fs.statSync(inDist("main.js")).isDirectory()).toBe(true); + } finally { + await close(); + } + }); + it("cleans the disk of each compiler of a multi-compiler", async () => { const memory = createMemoryFileSystem(); From c99f8f92a6c480ab749b7fc155340dea98ef776e Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:23:00 +0000 Subject: [PATCH 17/18] refactor: simplify the file system writing to disk Repeat every write on disk through one `mirror` instead of a wrapper per method, and remove from both and list both in a few lines. Ask the `keep` hook of `CleanPlugin` too before removing a disk copy of a file `writeToDisk` leaves out, as `output.clean` does, with `clean.keep` where the compiler's `CleanPlugin` has no hooks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- src/index.js | 441 ++++++++++++++----------------- test/write-to-disk-clean.test.js | 74 ++++++ types/index.d.ts | 2 + 3 files changed, 268 insertions(+), 249 deletions(-) diff --git a/src/index.js b/src/index.js index 4f555aca5..98f4c8cf1 100644 --- a/src/index.js +++ b/src/index.js @@ -21,6 +21,7 @@ const noop = () => {}; /** @typedef {import("schema-utils/declarations/validate").Schema} Schema */ /** @typedef {import("webpack").Compiler} Compiler */ /** @typedef {import("webpack").MultiCompiler} MultiCompiler */ +/** @typedef {import("webpack").Compilation} Compilation */ /** @typedef {import("webpack").Configuration} Configuration */ /** @typedef {import("webpack").Stats} Stats */ /** @typedef {import("webpack").MultiStats} MultiStats */ @@ -536,14 +537,11 @@ function isDiskFileSystem(fileSystem) { /** * The output file system webpack is given when `writeToDisk` writes to disk - * besides the file system files are served from. It writes to that one, and - * to disk the files `writeToDisk` takes, links, permissions and times - * included. Deletes reach both, and listings and `lstat` see the disk too, - * so webpack's own `output.clean` cleans the disk as it cleans its output: - * stale files from an earlier session, files a rebuild no longer emits, - * `clean.keep` and `clean.dry`. What webpack reads to decide whether to - * write a file comes from the served file system alone. A file `writeToDisk` - * leaves out is removed from disk when written, as `output.clean` would. + * besides the file system files are served from. Writes go to that one and, + * for the paths `writeToDisk` takes, to disk; removals reach both, and + * listings and `lstat` see the disk too. So webpack's own `output.clean` + * cleans the disk as it cleans its output. What webpack reads to decide + * whether to write a file comes from the served file system alone. * @template {IncomingMessage} Request * @template {ServerResponse} Response * @param {OutputFileSystem} outputFileSystem the file system files are served from @@ -552,6 +550,17 @@ function isDiskFileSystem(fileSystem) { * @returns {OutputFileSystem} the file system writing to both */ function createDiskWritingFileSystem(outputFileSystem, context, compilers) { + /** @type {EXPECTED_ANY} */ + const served = outputFileSystem; + /** @type {WeakMap} */ + const compilations = new WeakMap(); + + for (const compiler of compilers) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + compilations.set(compiler, compilation); + }); + } + /** * @param {string} targetPath absolute path of a file * @returns {boolean} true when it is written to disk @@ -563,286 +572,220 @@ function createDiskWritingFileSystem(outputFileSystem, context, compilers) { }; /** - * Whether `output.clean` would remove a file at this path, left on disk by an - * earlier session. The `keep` hook of `CleanPlugin` is not consulted here. - * @param {string} targetPath absolute path of a file - * @returns {boolean} true when it is cleaned + * Whether `output.clean` keeps a file in a compiler's output, decided as + * `CleanPlugin` decides it: its `keep` hook first, then `clean.keep`. + * @param {Compiler} compiler compiler + * @param {string} file path relative to the output, with `/` separators + * @returns {boolean} true when it is kept */ - const isCleaned = (targetPath) => - compilers.some(({ options, outputPath }) => { - const { clean } = options.output; + const isKept = (compiler, file) => { + const { clean } = compiler.options.output; - if (!clean || (typeof clean === "object" && clean.dry)) { - return false; - } + if (!clean || (typeof clean === "object" && clean.dry)) { + return true; + } - const relativePath = path.relative(outputPath, targetPath); + const compilation = compilations.get(compiler); + const { CleanPlugin } = compiler.webpack; + const byHook = + compilation && CleanPlugin && CleanPlugin.getCompilationHooks + ? CleanPlugin.getCompilationHooks(compilation).keep.call(file) + : undefined; - if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) { - return false; - } + if (byHook !== undefined) { + return byHook; + } - const keep = typeof clean === "object" ? clean.keep : undefined; - const file = relativePath.replaceAll("\\", "/"); + const keep = typeof clean === "object" ? clean.keep : undefined; - if (keep === undefined) { - return true; - } + if (keep === undefined) { + return false; + } - if (typeof keep === "string") { - return !file.startsWith(keep); - } + if (typeof keep === "string") { + return file.startsWith(keep); + } - if (keep instanceof RegExp) { - return !keep.test(file); - } + if (keep instanceof RegExp) { + return keep.test(file); + } - if (typeof keep === "function") { - return !keep(file); - } + if (typeof keep === "function") { + return Boolean(keep(file)); + } - // A glob condition is not matched here, so what it might keep is kept. - return false; - }); + // A glob condition is not matched here, so what it might keep is kept. + return true; + }; /** - * Run a write on disk once it succeeded on the served file system. - * @param {string} targetPath absolute path of the file - * @param {(callback: (err?: NodeJS.ErrnoException | null) => void) => void} write the write on disk - * @param {(err?: NodeJS.ErrnoException | null) => void} callback callback - * @returns {(err?: NodeJS.ErrnoException | null) => void} the callback of the write on the served file system + * Whether `output.clean` would remove a disk copy, left by an earlier + * session, of a file `writeToDisk` leaves out: one webpack counts as current. + * @param {string} targetPath absolute path of a file + * @returns {boolean} true when it is cleaned */ - const thenOnDisk = (targetPath, write, callback) => (err) => { - if (err) { - return callback(err); - } + const isCleaned = (targetPath) => + compilers.some((compiler) => { + const file = path.relative(compiler.outputPath, targetPath); - if (!takes(targetPath)) { - // A copy an earlier session wrote, which `output.clean` counts as current. - if (isCleaned(targetPath)) { - return fs.unlink(targetPath, () => callback()); - } + return ( + !file.startsWith("..") && + !path.isAbsolute(file) && + !isKept(compiler, file.replaceAll("\\", "/")) + ); + }); - return callback(); - } + /** + * A write on the served file system, repeated on disk for the paths + * `writeToDisk` takes once it succeeded there. + * @param {"writeFile" | "symlink" | "chmod" | "utimes"} name the method + * @param {number} pathIndex which argument is the path written + * @returns {(...args: EXPECTED_ANY[]) => void} the method + */ + const mirror = + (name, pathIndex) => + (...args) => { + const callback = args.pop(); + const targetPath = args[pathIndex]; + + served[name](...args, (/** @type {Error | null=} */ err) => { + if (err) { + return callback(err); + } + + if (!takes(targetPath)) { + return isCleaned(targetPath) + ? fs.unlink(targetPath, () => callback()) + : callback(); + } - const dir = path.dirname(targetPath); + const dir = path.dirname(targetPath); + const write = () => + /** @type {EXPECTED_ANY} */ (fs)[name]( + ...args, + (/** @type {Error | null} */ writeError) => { + if (writeError) { + context.logger.error( + `Unable to write "${targetPath}" asset to disk:\n${writeError}`, + ); - fs.mkdir(dir, { recursive: true }, (mkdirError) => { - if (mkdirError) { - context.logger.error( - `Unable to write "${dir}" directory to disk:\n${mkdirError}`, - ); + return callback(writeError); + } - return callback(mkdirError); - } + context.logger.log(`Asset written to disk: "${targetPath}"`); - write((writeError) => { - if (writeError) { - context.logger.error( - `Unable to write "${targetPath}" asset to disk:\n${writeError}`, + callback(); + }, ); - return callback(writeError); - } + fs.mkdir(dir, { recursive: true }, (mkdirError) => { + if (mkdirError) { + context.logger.error( + `Unable to write "${dir}" directory to disk:\n${mkdirError}`, + ); - context.logger.log(`Asset written to disk: "${targetPath}"`); + return callback(mkdirError); + } - return callback(); - }); - }); - }; + // A link replaces whatever was there, as webpack replaces it. + if (name === "symlink") { + return fs.unlink(targetPath, write); + } - /** @type {EXPECTED_ANY} */ - const served = outputFileSystem; + write(); + }); + }); + }; /** - * Remove from both, done once removed from either. - * @param {"unlink" | "rmdir"} method the removal - * @param {string} targetPath absolute path - * @param {(err?: NodeJS.ErrnoException | null) => void} callback callback + * A removal on both, done once either removed it. + * @param {"unlink" | "rmdir"} name the method + * @returns {(targetPath: string, callback: (err?: Error | null) => void) => void} the method */ - const removeFromBoth = (method, targetPath, callback) => { - let pending = 2; - let removed = false; - /** @type {NodeJS.ErrnoException | null | undefined} */ - let firstError; - /** - * @param {NodeJS.ErrnoException | null=} err err - */ - const done = (err) => { - if (!err) { - removed = true; - } else if (!firstError) { - firstError = err; - } - - pending -= 1; - - if (pending === 0) { - callback(removed ? null : firstError); - } - }; - - if (served[method]) { - served[method](targetPath, done); - } else { - pending -= 1; - } + const removeFromBoth = (name) => (targetPath, callback) => { + const run = (/** @type {EXPECTED_ANY} */ fileSystem) => + new Promise((resolve) => { + if (fileSystem[name]) { + fileSystem[name](targetPath, (/** @type {Error | null} */ err) => { + resolve(err || null); + }); + } else { + resolve(undefined); + } + }); - fs[method](targetPath, done); + Promise.all([run(served), run(fs)]).then((errors) => { + callback(errors.includes(null) ? null : errors.find(Boolean)); + }); }; - // What is not written here, such as `readFile`, `stat` and `mkdir`, reaches - // the served file system alone. A method webpack can do without, such as - // `symlink`, is kept only where the served file system has it. - /** @type {PropertyDescriptorMap} */ + // What is not here, such as `readFile`, `stat` and `mkdir`, reaches the + // served file system alone; `lstat` and `readdir` see the disk too, which is + // how `output.clean` finds what an earlier session left there. + /** @type {Record} */ const methods = { - writeFile: { - value: ( - /** @type {string} */ targetPath, - /** @type {Buffer} */ content, - /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, - ) => - served.writeFile( - targetPath, - content, - thenOnDisk( - targetPath, - (done) => fs.writeFile(targetPath, content, done), - callback, - ), - ), - }, - unlink: { - value: ( - /** @type {string} */ targetPath, - /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, - ) => removeFromBoth("unlink", targetPath, callback), - }, - rmdir: { - value: ( - /** @type {string} */ targetPath, - /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, - ) => removeFromBoth("rmdir", targetPath, callback), - }, - // How `output.clean` finds what is on disk alone, left from an earlier session. - lstat: { - value: ( - /** @type {string} */ targetPath, - /** @type {(err: NodeJS.ErrnoException | null, stats?: import("fs").Stats) => void} */ callback, - ) => - (served.lstat || served.stat).call( - served, - targetPath, - ( - /** @type {NodeJS.ErrnoException | null} */ err, - /** @type {import("fs").Stats} */ stats, - ) => { - if (err && err.code === "ENOENT") { - return fs.lstat(targetPath, callback); - } - - callback(err, stats); - }, - ), - }, - readdir: { - value: ( - /** @type {string} */ targetPath, - /** @type {(err: NodeJS.ErrnoException | null, entries?: string[]) => void} */ callback, - ) => { - /** - * @param {NodeJS.ErrnoException | null} servedError error from the served file system - * @param {string[]=} servedEntries entries on the served file system - * @returns {void} - */ - const withDisk = (servedError, servedEntries) => - fs.readdir(targetPath, (diskError, diskEntries) => { - if (servedError && diskError) { - return callback(servedError); - } - - callback(null, [ - ...new Set([...(servedEntries || []), ...(diskEntries || [])]), - ]); - }); + writeFile: mirror("writeFile", 0), + unlink: removeFromBoth("unlink"), + rmdir: removeFromBoth("rmdir"), + lstat: ( + /** @type {string} */ targetPath, + /** @type {(err: Error | null, stats?: EXPECTED_ANY) => void} */ callback, + ) => + (served.lstat || served.stat).call( + served, + targetPath, + ( + /** @type {NodeJS.ErrnoException | null} */ err, + /** @type {EXPECTED_ANY} */ stats, + ) => + err && err.code === "ENOENT" + ? fs.lstat(targetPath, callback) + : callback(err, stats), + ), + readdir: ( + /** @type {string} */ targetPath, + /** @type {(err: Error | null, entries?: string[]) => void} */ callback, + ) => { + /** + * @param {Error | null} servedError error from the served file system + * @param {string[]=} servedEntries entries on the served file system + * @returns {void} + */ + const withDisk = (servedError, servedEntries) => + fs.readdir(targetPath, (diskError, diskEntries) => + servedError && diskError + ? callback(servedError) + : callback(null, [ + ...new Set([...(servedEntries || []), ...(diskEntries || [])]), + ]), + ); - if (!served.readdir) { - return withDisk(null, []); - } + if (!served.readdir) { + return withDisk(null, []); + } - served.readdir(targetPath, withDisk); - }, + served.readdir(targetPath, withDisk); }, }; - if (served.symlink) { - methods.symlink = { - value: ( - /** @type {string} */ target, - /** @type {string} */ targetPath, - /** @type {"file" | "dir" | "junction"} */ type, - /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, - ) => - served.symlink( - target, - targetPath, - type, - thenOnDisk( - targetPath, - (done) => - fs.unlink(targetPath, () => - fs.symlink(target, targetPath, type, done), - ), - callback, - ), - ), - }; - } - - if (served.chmod) { - methods.chmod = { - value: ( - /** @type {string} */ targetPath, - /** @type {number} */ mode, - /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, - ) => - served.chmod( - targetPath, - mode, - thenOnDisk( - targetPath, - (done) => fs.chmod(targetPath, mode, done), - callback, - ), - ), - }; - } - - if (served.utimes) { - methods.utimes = { - value: ( - /** @type {string} */ targetPath, - /** @type {Date} */ atime, - /** @type {Date} */ mtime, - /** @type {(err?: NodeJS.ErrnoException | null) => void} */ callback, - ) => - served.utimes( - targetPath, - atime, - mtime, - thenOnDisk( - targetPath, - (done) => fs.utimes(targetPath, atime, mtime, done), - callback, - ), - ), - }; + // Methods webpack can do without stay out where the served file system lacks them. + for (const [name, pathIndex] of /** @type {const} */ ([ + ["symlink", 1], + ["chmod", 0], + ["utimes", 0], + ])) { + if (served[name]) { + methods[name] = mirror(name, pathIndex); + } } return /** @type {OutputFileSystem} */ ( - Object.create(outputFileSystem, methods) + Object.create( + outputFileSystem, + Object.fromEntries( + Object.entries(methods).map(([name, value]) => [name, { value }]), + ), + ) ); } diff --git a/test/write-to-disk-clean.test.js b/test/write-to-disk-clean.test.js index 6e026c619..70e6dd816 100644 --- a/test/write-to-disk-clean.test.js +++ b/test/write-to-disk-clean.test.js @@ -1083,6 +1083,80 @@ describe("output.clean with writeToDisk", () => { }); } + it("keeps the copy on disk of a file the function leaves out when a plugin keeps it through the `keep` hook", async () => { + createPublic(); + fs.writeFileSync(inDist("robots.txt"), "old"); + + const memory = createMemoryFileSystem(); + const keeper = { + apply(compiler) { + compiler.hooks.thisCompilation.tap("test", (compilation) => { + webpack.CleanPlugin.getCompilationHooks(compilation).keep.tap( + "test", + (file) => (file === "robots.txt" ? true : undefined), + ); + }); + }, + }; + const compiler = createCompiler( + { clean: true, copy: [{ from: "public" }] }, + [keeper], + ); + const { instance, close } = start( + compiler, + { + writeToDisk: (targetPath) => targetPath.endsWith(".js"), + outputFileSystem: memory, + }, + isPlugin, + ); + + try { + await built(instance); + + expect(readDist("robots.txt")).toBe("old"); + expect(memory.readFileSync(inDist("robots.txt"), "utf8")).toBe( + "v1", + ); + } finally { + await close(); + } + }); + + it("keeps the copy on disk of a file the function leaves out by `clean.keep` alone where `CleanPlugin` has no hooks", async () => { + createPublic(); + fs.writeFileSync(inDist("robots.txt"), "old"); + fs.writeFileSync(inDist("humans.txt"), "old"); + changePublic("humans.txt", "v1"); + + const memory = createMemoryFileSystem(); + const compiler = createCompiler({ + clean: { keep: /^robots/ }, + copy: [{ from: "public" }], + }); + + // As a compiler whose `CleanPlugin` offers no `keep` hook to ask. + compiler.webpack = { ...compiler.webpack, CleanPlugin: undefined }; + + const { instance, close } = start( + compiler, + { + writeToDisk: (targetPath) => targetPath.endsWith(".js"), + outputFileSystem: memory, + }, + isPlugin, + ); + + try { + await built(instance); + + expect(readDist("robots.txt")).toBe("old"); + expect(fs.existsSync(inDist("humans.txt"))).toBe(false); + } finally { + await close(); + } + }); + it("removes from disk the copies of what the function leaves out, for each compiler of a multi-compiler", async () => { for (const name of ["a", "b"]) { fs.mkdirSync(inDist(name), { recursive: true }); diff --git a/types/index.d.ts b/types/index.d.ts index 995090792..ee2b698d7 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -23,6 +23,7 @@ declare namespace wdm { Schema, Compiler, MultiCompiler, + Compilation, Configuration, Stats, MultiStats, @@ -139,6 +140,7 @@ declare function honoWrapper< type Schema = import("schema-utils/declarations/validate").Schema; type Compiler = import("webpack").Compiler; type MultiCompiler = import("webpack").MultiCompiler; +type Compilation = import("webpack").Compilation; type Configuration = import("webpack").Configuration; type Stats = import("webpack").Stats; type MultiStats = import("webpack").MultiStats; From 8709d952a63b9bf0dc5cef69dd02f32177e42b75 Mon Sep 17 00:00:00 2001 From: alexander-akait <4567934+alexander-akait@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:32:43 +0000 Subject: [PATCH 18/18] docs: note how to replace the disk-writing file system in the next major Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA --- src/index.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/index.js b/src/index.js index 98f4c8cf1..3bc051c84 100644 --- a/src/index.js +++ b/src/index.js @@ -535,6 +535,12 @@ function isDiskFileSystem(fileSystem) { ); } +// TODO in the next major release replace this file system with one of: +// - a webpack hook for additional outputs, where the middleware adds the disk +// with `writeToDisk` as its filter and webpack writes and cleans both itself; +// - a file system helper webpack exports, mirroring one file system to another; +// - `writeToDisk: true` only, with the disk as webpack's only output and files +// served from it; deprecate the function form first, as it needs this layer. /** * The output file system webpack is given when `writeToDisk` writes to disk * besides the file system files are served from. Writes go to that one and,