From 12ecab44fccef88e8f00e52e030d2ce395d4cf36 Mon Sep 17 00:00:00 2001 From: Ivan Kopeykin Date: Tue, 1 Mar 2022 20:22:07 +0300 Subject: [PATCH] use cache in BannerPlugin --- lib/BannerPlugin.js | 14 +++++++++---- test/BannerPlugin.test.js | 41 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 4 deletions(-) create mode 100644 test/BannerPlugin.test.js diff --git a/lib/BannerPlugin.js b/lib/BannerPlugin.js index 81b765831b1..3c10558acc4 100644 --- a/lib/BannerPlugin.js +++ b/lib/BannerPlugin.js @@ -77,6 +77,7 @@ class BannerPlugin { undefined, options ); + const cache = new WeakMap(); compiler.hooks.compilation.tap("BannerPlugin", compilation => { compilation.hooks.processAssets.tap( @@ -102,10 +103,15 @@ class BannerPlugin { const comment = compilation.getPath(banner, data); - compilation.updateAsset( - file, - old => new ConcatSource(comment, "\n", old) - ); + compilation.updateAsset(file, old => { + let cached = cache.get(old); + if (!cached || cached.comment !== comment) { + const source = new ConcatSource(comment, "\n", old); + cache.set(old, { source, comment }); + return source; + } + return cached.source; + }); } } } diff --git a/test/BannerPlugin.test.js b/test/BannerPlugin.test.js new file mode 100644 index 00000000000..46ae674fcff --- /dev/null +++ b/test/BannerPlugin.test.js @@ -0,0 +1,41 @@ +"use strict"; + +const path = require("path"); +const fs = require("graceful-fs"); + +const webpack = require(".."); + +it("should cache assets", done => { + const entry1File = path.join(__dirname, "js", "BannerPlugin", "entry1.js"); + const entry2File = path.join(__dirname, "js", "BannerPlugin", "entry2.js"); + try { + fs.mkdirSync(path.join(__dirname, "js", "BannerPlugin"), { + recursive: true + }); + } catch (e) { + // empty + } + const compiler = webpack({ + mode: "development", + entry: { + entry1: entry1File, + entry2: entry2File + }, + output: { + path: path.join(__dirname, "js", "BannerPlugin", "output") + }, + plugins: [new webpack.BannerPlugin("banner is a string")] + }); + fs.writeFileSync(entry1File, "1", "utf-8"); + fs.writeFileSync(entry2File, "1", "utf-8"); + compiler.run(err => { + if (err) return done(err); + fs.writeFileSync(entry2File, "2", "utf-8"); + compiler.run((err, stats) => { + const { assets } = stats.toJson(); + expect(assets.find(as => as.name === "entry1.js").emitted).toBe(false); + expect(assets.find(as => as.name === "entry2.js").emitted).toBe(true); + done(err); + }); + }); +});