Deploying Vue.js apps to GitHub Pages with an npm script

In rewriting Auroras.live, I switched to Vue.js. This was done for a few reasons, mostly as a learning exercise, but also because it felt lighter than Angular, plus there’s a lot of code sharing due to the website, the mobile app and parts of the new API’s front end being written in Vue.

One goal I had for the rewrite was to make it easier to manage. I wanted one command to build and deploy the website to match the significantly cleaner code base so I wouldn’t have to SSH into my server and git pull any changes down, and thanks to Vue’s npm run build and GitHub Pages, this can be done.

I changed my scripts section of package.json to look like this:

  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "deploy": "rm -rf dist && npm run build && cd dist && git init && git add . && git commit -m \"Deploy via script\" && git remote add origin https://github.com/username/myrepo.git && git push --force origin master:gh-pages"
  },

And now when I want to deploy a new version of my site, I can just run npm run deploy from the command line, and within a minute or two I have a new version of the website, ready to go.

I used this for a bit, but then decided I wanted to “timestamp” the build so the end user could see when the site was last updated. I could have done this manually, but that would be an extra step. So instead I set up an export in my vue.config.js file:

process.env.VUE_APP_VERSION = Date().toString()

And then in my App.vue file I added the environment variable:

data() {
    return {
      // ...
      version: process.env.VUE_APP_VERSION,
      // ...
    }
}

And finally I added {{ version }} to the template. Now when I run npm run build, the date the site was built is hard-coded into the site

I plan to write similar scripts for the app, so be sure to check back to see my progress.

Leave a Reply