Skip to content

Commit

Permalink
Store hooks as property of compilation
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
GeorgeTaveras1231 authored Jan 3, 2025
1 parent 7299866 commit 556c75b
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>, css: Array<string>, manifest?: string, favicon?: string }} AssetsInformationByGroups */
/** @typedef {import("./typings").Hooks} HtmlWebpackPluginHooks */
/**
* @type {WeakMap<Compilation, HtmlWebpackPluginHooks>}}
*/
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
Expand Down Expand Up @@ -98,7 +96,7 @@ class HtmlWebpackPlugin {
* @returns {HtmlWebpackPluginHooks}
*/
static getCompilationHooks(compilation) {
let hooks = compilationHooksMap.get(compilation);
let hooks = compilation[compilationHooksSymbol];

if (!hooks) {
hooks = {
Expand All @@ -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;
Expand Down

0 comments on commit 556c75b

Please sign in to comment.