How to show Vue.js app version in templates

in Code Write a comment

In this tutorial, you’ll learn how to display your current app version in templates. It can be useful to know the app version e.g. for your client, other developers or users.

This option will allow you to show the package.json app version anywhere in your app automatically.

Set global variable

Firstly, let’s create a new global variable in Vue.js PACKAGE_JSON that will contain the entire package.json as a string.

// dev.env.js
module.exports = {
  NODE_ENV: '"development"',
  VUE_APP_BASE_URL: '"https://life.renatello.com/"',
  PACKAGE_JSON: '"' + escape(JSON.stringify(require('../package.json'))) + '"'
}

As you can see, there’s a PACKAGE_JSON variable that we can use in our app.


Hi, I'm Renat 👋

 


Print the app version

There are two ways that you can use to print the app version.

Using Vuex

If you’re familiar with Vuex and use it in your app, this is the best place for your app version. Vuex will make it accessible throughout your app.

// Vuex
const state = {
  packageVersion: JSON.parse(unescape(process.env.PACKAGE_JSON || '%7Bversion%3A0%7D')).version,
  // ...
}

const getters = {
  appVersion: (state) => {
    return state.packageVersion
  }
  // ...
}

There’s a fallback option so that the code doesn’t generate any options if it fails to import package.json.

'%7Bversion%3A0%7D'

Will print as:

{
  version: 0
}

Now, if you want to print the app version in HTML template you can just do this:

{{ $store.getters.appVersion }}

Or access it as a computed property.

appVersion () {
  return this.$store.getters.appVersion
} 

Using computed property

If you’re not using Vuex you can directly access the current app version using the computed property.

appVersion() {
  return JSON.parse(unescape(process.env.PACKAGE_JSON || '%7Bversion%3A0%7D')).version;
}

If you find this post useful, please let me know in the comments below and subscribe to my newsletter. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vuejs-app-version

PS: Make sure you check other Vue.js tutorials, e.g. how to password protect your website in Vue.js, how to deploy Vue.js app to Firebase hosting.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment