From 556c75b12bc19cf30909f8018dc8edc9e638aad4 Mon Sep 17 00:00:00 2001 From: George Date: Fri, 3 Jan 2025 11:01:42 -0500 Subject: [PATCH] Store hooks as property of compilation This allows reading the hooks more reliably. Using a WeakMap in a closure causes issues if multiple versions of html-webpack-plugin are installed because it requires that plugins that tap into these hooks use the version of this package that is resolved by the webpack config. This may be a common issue in monorepos. Using a global symbol allows any version of `html-webpack-plugin` to resolve the hooks used in the compilation, allows plugins in monorepos to work more seamlessly. --- index.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index 7ce48402..b436bee0 100644 --- a/index.js +++ b/index.js @@ -30,10 +30,8 @@ const { AsyncSeriesWaterfallHook } = require("tapable"); /** @typedef {Array<{ name: string, source: import('webpack').sources.Source, info?: import('webpack').AssetInfo }>} PreviousEmittedAssets */ /** @typedef {{ publicPath: string, js: Array, css: Array, manifest?: string, favicon?: string }} AssetsInformationByGroups */ /** @typedef {import("./typings").Hooks} HtmlWebpackPluginHooks */ -/** - * @type {WeakMap}} - */ -const compilationHooksMap = new WeakMap(); + +const compilationHooksSymbol = Symbol.for('html-webpack-plugin/compilation-hooks'); class HtmlWebpackPlugin { // The following is the API definition for all available hooks @@ -98,7 +96,7 @@ class HtmlWebpackPlugin { * @returns {HtmlWebpackPluginHooks} */ static getCompilationHooks(compilation) { - let hooks = compilationHooksMap.get(compilation); + let hooks = compilation[compilationHooksSymbol]; if (!hooks) { hooks = { @@ -109,7 +107,9 @@ class HtmlWebpackPlugin { beforeEmit: new AsyncSeriesWaterfallHook(["pluginArgs"]), afterEmit: new AsyncSeriesWaterfallHook(["pluginArgs"]), }; - compilationHooksMap.set(compilation, hooks); + Object.defineProperty(compilation, compilationHooksSymbol, { + value: hooks, + }) } return hooks;