html-webpack-plugin icon indicating copy to clipboard operation
html-webpack-plugin copied to clipboard

Allow plugin to run during a custom stage, or change default

Open issacgerges opened this issue 1 year ago • 1 comments

Is your feature request related to a problem? Please describe. I've created a custom plugin that adds SRI hashes for all inline script and style tags in my generated HTML. Some of these scripts include asset urls (which are plumbed in via templateParams). Due to webpack 5's recent introduction of [contenthash] and the RealContentHashPlugin, my hash generation now happens at the wrong time (before the hashes are replaced with their final calculated value). This difference between the hash and final outputted content prevents the browser from running the code in these tags.

I was able to resolve this by patching HtmlWebpackPlugin to modify the stage it itself registers on, but I'd rather not maintain this patch and wonder if this would solve any other problems

diff --git a/index.js b/index.js
index 4452f63631ab919e09dbad0f9d721e493fb5802c..ebae860db2d30b51ceafe59aa4cefe5c1d68ea8a 100644
--- a/index.js
+++ b/index.js
@@ -266,9 +266,9 @@ function hookIntoCompiler (compiler, options, plugin) {
           name: 'HtmlWebpackPlugin',
           stage:
           /**
-           * Generate the html after minification and dev tooling is done
+           * Generate the html after minification and dev tooling is done, or after contenthash replacement in webpack@5
            */
-          webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
+          webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH ? webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH + 1 : webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
         },
         /**
          * Hook into the process assets hook

Describe the solution you'd like I'd love to see this registered stage change, or a config param allowing me to specify a custom stage to register on

Describe alternatives you've considered Just owning my patch forever 😄

Additional context n/a

issacgerges avatar Mar 07 '24 14:03 issacgerges

I don't think we should change stage, can you create reproducible example with your custom plugin, I will investigate

alexander-akait avatar Mar 07 '24 14:03 alexander-akait

This issue is trying to resolve #1638, which is caused by Webpack 5's contenthash change: https://github.com/webpack/webpack/issues/9520.

lancelotj avatar Apr 19 '24 16:04 lancelotj

let's close in favor https://github.com/jantimon/html-webpack-plugin/issues/1638

alexander-akait avatar Apr 22 '24 18:04 alexander-akait