Logo for Johan Baaij Software Development

Johan Baaij

is developing software for the web with Ruby on Rails, Vue.js and other open-source technologies.

Displaying a Git commit SHA in your Nuxt.js application

#100DaysOfCode day 15

Tue Apr 21 2020

Why?

For some applications it may be useful to know the current commit at the time of deployment. This information can be used in bug reports or to provide a link to the specific commit on GitHub.

The commit hash

A git commit has a 40 character identifier that is usually referred to as the "SHA" or "hash". This is how you display the hash in your terminal.

$ git rev-parse HEAD
f2faa06edfc89db696b6be4184f57e8d0cbe9d97

It's possible to abbreviate the hash with the --short modifier.

$ git rev-parse --short HEAD
f2faa06

You can navigate to the commit on GitHub by appending the hash to this URL.

https://github.com/[username]/[reponame]/commit/f2faa06

It will work with both the long and short version, as long as the commit has been pushed.

Setting an environment variable with the commit hash

A Nuxt.js application knows nothing about its Git repository. That's why we will introduce a current-git-sha script and prepend it to dev, build and generate. Running the new script stores the output of rev-parse in a `NUXT_ENV_` variable which will then be injected into the application.

// package.json
{
  "name": "personal-website",
  "scripts": {
    // New script
    "current-git-sha": "NUXT_ENV_CURRENT_GIT_SHA=`git rev-parse --short HEAD`",
    
    // Runs the new script + original dev script
    "dev": "yarn run current-git-sha nuxt",
    
    // Runs the new script + original build script
    "build": "yarn run current-git-sha nuxt build",
    
    // Runs the new script + original generate script
    "generate": "yarn run git-env-sha nuxt generate",
    
    "start": "nuxt start",
    "lint": "eslint --ext .js,.vue --ignore-path .gitignore .",
    "test": "jest"
    }
  }
}

The commit hash will now be available as process.env.NUXT_ENV_CURRENT_GIT_SHA. Here's how you would use it in a component. Note that at build-time the variable will be replaced with the hash.

<template>
  <footer>
    <a :href="`https://github.com/[username]/[reponame]/commit/${commitSha}`">
      {{ commitSha }}
    </a>
  </footer>
</template>

<script>
  export default {
    data() {
      return {
        commitSha: process.env.NUXT_ENV_CURRENT_GIT_SHA
      };
    }
  };
</script>

Notes & resources


This post was written as part of my #100DaysOfCode challenge, day 15.