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:
- In
package.jsonwe hand-codebase_version - We generate
final_versionelsewhere and setversioninpackage.jsonto its value:- if we are on a release tag
vX.Y.Zfinal_versiontakes this value - otherwise we take
base_versionand append the short git revision
- if we are on a release tag
- We regenerate
src/version.js(and optionallysrc/version.cjs) and add these files to.gitignore
Now we can just import version where its needed and we have the version in
javascript.