geoffwilliams@home:~$

Exposing version in JavaScript

Sometimes you want to expose the version number from package.json to your app so you can write code like this:

console.log"Express server listening on port %d in %s mode %s", app.address().port, app.settings.env, app.VERSION

This isn’t my code - there’s a whole discussion about how to export the version without having to include package.json over on stackoverflow

Turns out the safest way to get the version number is to generate src/version.js file during build. You may also need to generate src/version.cjs if your using Babel.

The stackoverflow discussion lists a few different ways to generate these files including a native JavaScript package, genversion.

Since I’m already using GNU Make for all my projects its easy to just generate the files using shell scripts, like this:

base_version := $(shell jq .base_version package.json)


package.json: must_rebuild
	cat <<< $$(jq ".version = \"$(final_version)\"" package.json) > package.json

src/version.js: must_rebuild
	echo "// ***** automatically generated. Do not edit! *****" > src/version.js
	echo "export default \"$(final_version)\";" >> src/version.js

src/version.cjs: must_rebuild
	echo "// ***** automatically generated. Do not edit! *****" > src/version.cjs
	echo "module.exports = \"$(final_version)\";" >> src/version.cjs

There’s a few things going on here:

  1. In package.json we hand-code base_version
  2. We generate final_version elsewhere and set version in package.json to its value:
    • if we are on a release tag vX.Y.Z final_version takes this value
    • otherwise we take base_version and append the short git revision
  3. We regenerate src/version.js (and optionally src/version.cjs) and add these files to .gitignore

Now we can just import version where its needed and we have the version in javascript.

Further reading

Post comment