From a89615e87d45cc565fda2dc7bd45a09b1e39db8d Mon Sep 17 00:00:00 2001 From: Peter Xu Date: Sun, 7 Nov 2021 13:09:10 -0800 Subject: [PATCH] fix: only have the stream close after writing Webpack filesystem caches --- index.js | 28 ++++++++++++++++++++++------ test/test.js | 32 +++++++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/index.js b/index.js index be4ec13..6e8a0dd 100644 --- a/index.js +++ b/index.js @@ -190,12 +190,28 @@ module.exports = function (options, wp, done) { } self.emit('compilation-error', compilationError); } - if (!isInWatchMode) { - self.queue(null); - } - done(err, stats); - if (isInWatchMode && !isSilent) { - fancyLog('webpack is watching for changes'); + if (isInWatchMode) { + done(err, stats); + if (!isSilent) { + fancyLog('webpack is watching for changes'); + } + } else { + function closeStream() { + self.queue(null); + done(err, stats); + } + + if (compiler.close) { + // For Webpack v5 and above: + // From https://webpack.js.org/api/node/#run: we need to close + // the compiler so that low-priority (e.g., caching) work happens + compiler.close(closeStream); + } else { + // Webpack v4 doesn't have compiler.close, so just immediately end + // the stream + // (see https://github.com/webpack/webpack/blob/v4.0.0/lib/Compiler.js) + closeStream(); + } } }; diff --git a/test/test.js b/test/test.js index 69f345d..3536eaf 100644 --- a/test/test.js +++ b/test/test.js @@ -3,6 +3,7 @@ const webpack = require('../'); const path = require('path'); const fs = require('vinyl-fs'); const named = require('vinyl-named'); +const nodeFS = require('fs'); const base = path.resolve(__dirname, 'fixtures'); @@ -93,7 +94,7 @@ test('stream multiple entry points', function (t) { test('empty input stream', function (t) { t.plan(1); - const entry = fs.src('test/path/to/nothing', { allowEmpty: true }); + const entry = fs.src('test/path/to/nothing', {allowEmpty: true}); const stream = webpack({ config: {}, quiet: true @@ -199,3 +200,32 @@ test('error formatting', function (t) { }); entry.pipe(stream); }); + +test('writes filesystem cache files', function (t) { + t.plan(2); + const entry = fs.src('test/fixtures/entry.js'); + const cacheDirectory = path.join(__dirname, 'testCache'); + + nodeFS.rmdirSync(cacheDirectory, {recursive: true, force: true}); + t.equal(nodeFS.existsSync(cacheDirectory), false, 'cache directory should not exist at start'); + + const stream = webpack({ + config: { + mode: 'development', + output: {filename: 'bundle.js'}, + cache: { + type: 'filesystem', + idleTimeoutForInitialStore: 0, + cacheDirectory + }, + }, + quiet: true + }); + + stream.on('end', function () { + t.equal(nodeFS.existsSync(cacheDirectory), true, 'should have created a cache directory after compile'); + nodeFS.rmdirSync(cacheDirectory, {recursive: true, force: true}); + }); + + entry.pipe(stream); +});