The doco for npm version
is at https://docs.npmjs.com/cli/version.
It says (my emphasis):
- Run the version script. These scripts have access to the new version in package.json (so they can incorporate it into file headers in generated files for example). Again, scripts should explicitly add generated files to the commit using git add.
How do you get this version from package.json. With a combination of grep, tr, ..
shell commands or in a variable? I tried %s
that is used for the git tag
and $npm.version
and $npm_package_version
but none worked.
I ended up using this, which works well:
"script": {
....
"postversion": "version=$(git-semver-tags | head -1); echo \"export const config = { version: '$version' }\" > client/src/app/config-from-npm.ts",
....
}
EDIT note that I changed the above from 'version' to 'postversion' since the new git tag
is not available until after version and I changed to git-semver-tags
since git tags
lists them lexically (so 0.0.1 comes before 0.0.20).
My solution shows that I had to use git-semver-tags
. The question is - Is there a proper way to get the version from package.json as the doco states?
I feel that the doco should be updated. I thought i'd create an issue against the https://github.com/npm/cli project but there is no 'issues' link (at least for me). It is a new git repository after a recent move from a different project so perhaps someone forgot to tick that box!
(Edit) I have a separate question for how to write .json/.js/.ts files from NPM. How to output JSON in NPM Script (now solved).