Search code examples
webpackwebpack-2html-webpack-plugin

Use compilation hash within js file


I use HtmlWebpackPlugin to generate my index.html through template. In there I write

var compilationHash = <%= webpack.hash %>

But this is of course in the html file. Similarly, I want to access the same hash in the bundle file. But obviously webpack is not available there. Is there a way to somehow provide webpack.hash into the file so I can access it just like the way I do var something = process.env.SOMETHING?

I hoped ProvidePlugin could be handy here, but not sure how I can access compilation hash in there.


Solution

  • So this is a bit chicken and egg. In order to generate the content hash, webpack needs to know all the content, yet if it were able to then inject the hash into the bundle itself as a variable, the content hash would then be different to that it has already calculated.

    While I'm dubious as to why you would need the hash itself inside the bundle, you can access the variable you have assigned in your HTML from inside the bundle with no need for plugins, via webpack's global.

    This is assigned by webpack to whatever scope the bundle itself has been is executed within, in a webpage like yours that would be window, so you can access your variable via global.compilationHash

    This has the caveat of only being available at runtime, and will always be undefined unless you provide it (ie if needed in your tests you will need to provide it to the test runner scope before you execute the code that uses it)