I've actually been through most of the solutions here and they either did not work on both Windows and Linux/OSX, or didn't work at all, or relied on Unix shell tools like grep/awk/sed.
The accepted answer works technically, but it sucks your whole package.json into your build and that's a Bad Thing that only the desperate should use, temporarily to get unblocked, and in general should be avoided, at least for production code. One alternative is to use that method only to write the version to a single constant that can be used as a source file for the build, instead of the whole file.
So for anyone else looking for a cross-platform solution (not reliant on Unix shell commands) and local (without external dependencies):
Since it can be assumed that Node.js is installed, and it's already cross-platform for this, I just created a make_version.js
file (or make_version.cjs
in more recent environments) with:
const PACKAGE_VERSION = require("./package.json").version;
console.log(`export const PACKAGE_VERSION = "${PACKAGE_VERSION}";`);
console.error("package.json version:", PACKAGE_VERSION);
and added a version
command to package.json
:
scripts: {
"version": "node make_version.js > src/version.js",
or
scripts: {
"version": "node make_version.cjs > src/version.js",
(for a CommonJS file) and then added:
"prebuild": "npm run version",
"prestart": "npm run version",
and it creates a new src/versions.js
on every start
or build
. Of course this can be easily tuned in the version
script to be a different location, or in the make_version.js
file to output different syntax and constant name, etc.
Note also that the pnpm package manager does not automatically run "pre" scripts, so you might need to adjust it for two commands if using that PM.
console.log(process.version)