'injecting a filename containing content hash into html generated by html-webpack-plugin

I'm working on a project that uses the html-webpack-plugin (plus the handlebars-loader) to render a handlebars template into an index.html. Straightforward enough.

We are also using a different plugin (the svg-spritemap-webpack-plugin, but the specifics are unimportant) to generate an SVG map file.

We would love for the generated svg map to have a content hash in the filename, and for it to be included via <img> tag in the index.html. That way all the svgs are not directly embedded into the html, reducing the html size and facilitating cacheing. Change the svgs and the content hash will change, browsers will then fetch a new copy. Great.

The issue is: How can we figure out what this svg map will be called so that we can inject the link into our html?

Our first thought was to try and write a handlebars helper which would look up the filename after it has been generated. We thought we could use the webpack-manifest-plugin or even just look in the build directory with a regex. Unfortunately, by default the html-webpack-plugin runs quite early, long before the svg file exists. Even writing a custom plugin which uses an compilation.hooks.processAssets.intercept({...}) to change the tap.stage of the HtmlWebpackPlugin to something like PROCESS_ASSETS_STAGE_REPORT, or even just a really large value like 20k, doesn't help. The svg file still don't exist to be found when the html is generated.

I feel like this should be a super simple task and that I'm just missing something really obvious... any help would be greatly appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source