Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Store hooks as property of compilation #1869

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

GeorgeTaveras1231
Copy link

@GeorgeTaveras1231 GeorgeTaveras1231 commented Jan 3, 2025

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.

Current workaround

I work in a monorepo where I've implemented a couple of plugins that tap in the html-webpack-plugin hooks. To bypass the issues I'm encountering, I defer the loading of html-webpack-plugin to the execution of the plugin, and use the context of the compilation to require to appropriate instance of html-webpack-plugin

- import HtmlWebpackPlugin from 'html-webpack-plugin';
+ import { createRequire } from 'node:module';
+ import path from 'node:path';

class MyHTMLPlugin {
  apply(compiler) {
    compiler.hooks.compilation.tap('MyHTMLPlugin', (compilation) => {
+    const require = createRequire(path.resolve(compiler.options.context, 'webpack.config.js');
+    const HtmlWebpackPlugin = require('html-webpack-plugin');
      const hooks = HtmlWebpackPlugin.getCompilationHooks(compilation);
      hooks.beforeEmit.tap('MyHTMLPlugin', () => { /* Omitted */ });
    });
  }
}

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.
@jantimon
Copy link
Owner

jantimon commented Jan 4, 2025

I don't think that the html-webpack-plugin should alter the webpack compilation object

What about passing the html-webpack-plugin to the custom plugin?

class MyHTMLPlugin {
  constructor(plugin) {
    this.plugin = plugin
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants