Adding the git commit hash to my Vite build
This was inspired by something we do at work. We want to be able to very easily confirm the version of our web application running in our production environment. We do this by injecting the git hash of the commit the build is generated from in an HTML comment.
I wanted to do the same thing with Vite. In a way compatible with GitHub pages.
TLDR: this commit implements my solution.
I am using a feature of Vite they call HTML Constant Replacement. This allows me to simply write a variable name into the index.html entrypoint. Though only variables that are made available on import.meta.env
by having a specific prefix.
Next it is good to know that the constant will not be replaced if there is no value in your build environment. There also did not seem to be a way to set a default. Unless the variable is not taken from the environment at all, but set by Vite itself during build.
At the bottom of the envPrefix
documentation I linked above, there is a little note that tells us we can use define
to write out own import.meta.env
values. So that is what I do:
{
// ... other settings of vite.config.mts
define: {
"import.meta.env.VITE_COMMIT_HASH": JSON.stringify(commit),
},
}
Now I can define where commit
comes from, and give it its own fallback:
const commit = process.env["COMMIT_HASH"] ?? "<unknown>";
With Vite instructed, now we need to get the actual hash. Luckily it is already available to us in the GitHub Workflow.
The checkout action that is used to grab the contents of the repository into the workflow container exposes a commit
variable. Whenever you are using prebuilt actions, it is always worth checking their output.
We add this output as the COMMIT_HASH
environment variable that was being extracted by my build code through the workflow YAML:
env:
COMMIT_HASH: ${{ steps.checkout.outputs.commit }}
Success!