diff --git a/src/clean-webpack-plugin.test.ts b/src/clean-webpack-plugin.test.ts index ec243e0..f7e433c 100644 --- a/src/clean-webpack-plugin.test.ts +++ b/src/clean-webpack-plugin.test.ts @@ -854,6 +854,54 @@ describe('cleanAfterEveryBuildPatterns option', () => { ]); }); + test('does not remove stale webpack asset with negative pattern match', async () => { + createSrcBundle(2); + createStaticFiles(); + + const cleanWebpackPlugin = new CleanWebpackPlugin({ + cleanAfterEveryBuildPatterns: ['!1.bundle.js'], + }); + + const compiler = webpack({ + entry: entryFileFull, + output: { + path: outputPathFull, + filename: 'bundle.js', + chunkFilename: '[name].bundle.js', + }, + plugins: [cleanWebpackPlugin], + }); + + expect(cleanWebpackPlugin.currentAssets).toEqual([]); + + await compiler.run(); + + expect(cleanWebpackPlugin.currentAssets).toEqual([ + '1.bundle.js', + 'bundle.js', + ]); + + expect(sandbox.getFileListSync(outputPathFull)).toEqual([ + '1.bundle.js', + 'bundle.js', + ]); + + createSrcBundle(1); + createStaticFiles(); + + await compiler.run(); + + expect(cleanWebpackPlugin.currentAssets).toEqual(['bundle.js']); + + expect(sandbox.getFileListSync(outputPathFull)).toEqual([ + '.hidden.file', + '1.bundle.js', + 'bundle.js', + 'static1.js', + 'static2.txt', + ]); + }); + test('handles the cleanAfterEveryBuildPatterns outside of webpack output directory', async () => { createSrcBundle(1); diff --git a/src/clean-webpack-plugin.ts b/src/clean-webpack-plugin.ts index bf8928d..42b1ab5 100644 --- a/src/clean-webpack-plugin.ts +++ b/src/clean-webpack-plugin.ts @@ -249,18 +249,24 @@ class CleanWebpackPlugin { */ this.currentAssets = assets.sort(); + const removePatterns = []; + /** * Remove unused webpack assets */ if (this.cleanStaleWebpackAssets === true && staleFiles.length !== 0) { - this.removeFiles(staleFiles); + removePatterns.push(...staleFiles); } /** - * Run cleanAfterEveryBuildPatterns + * Remove cleanAfterEveryBuildPatterns */ if (this.cleanAfterEveryBuildPatterns.length !== 0) { - this.removeFiles(this.cleanAfterEveryBuildPatterns); + removePatterns.push(...this.cleanAfterEveryBuildPatterns); + } + + if (removePatterns.length !== 0) { + this.removeFiles(removePatterns); } }