I want to reference my package version in a npm script so I can show current version in the app. Something like
{
"name": "bla",
"version": "1.0.0",
"author": "bla bla",
"scripts": {
"build": "node VERSION=<<package.version>> build/build.js"
}
}
Is there a way to do this?
1) Referencing package version in npm-scripts.
In
npm-script
's you can reference theversion
using the variablenpm_package_version
. For example:Using a bash shell (E.g. Linux, macOS):
Note the
$
prefixUsing Windows (E.g. cmd.exe, Powershell):
Note the
%
prefix and suffixCross platform
To utilize one syntax cross-platform check out the package cross-var
2) Referencing package version in node script.
The package version can also be referenced in your a app/node script (i.e.
build.js
) as follows:3) Replacing a placeholder string in a .js file with package version.
Another way to achieve this is to specify a placeholder text string within your JavaScript file. Lets say we have a file named
build.js
and within that file we have a variable namedVERSION
declared as follows:As you can see, the placeholder text string is
@VERSION@
.You can then install and utilize the package called replace in an npm-script as follows:
Running
npm run add-version
will replace the instance of@VERSION@
with the package version (i.e.1.0.0
), in the file namedbuild.js
. This solution will hard-code the npm package version into the resultant file.Note: The to string in the
add-version
script (above) currently uses the$
prefix (i.e.$npm_package_version
) to access the variable, so this will only run successfully on a bash shell. However, for cross-platform usage you'll need to usecross-var
as explained in section one (above). In which case theadd-version
script can be defined as follows: