Keeping version numbers in sync in angular library project package.json files
I've seen people ask the same question to vsavkin (Nrwl/Nx dude) and his response was a fairly involved git sub-module approach.
While this workflow is a little complex, it does allow shared libraries to be individually versioned whilst keeping them in the same parent git-repo.
A simpler alternative is, as you have already mentioned, to keep all libraries in a monorepo the same version as the root package.json - similar to how the Angular monorepo bumps its versions of all the Angular packages at the same time.
This can be done easily in node, or in bash/shell with a little bit more scripting.
Here's a gist with node, bash & shell examples of how to extract the version from the root package.json.
To actually bump the versions of the packages here's a simple approach: install this npm package (a nice CLI for editing json files) and read the In-Place editing section. You should now have all the tools you need!
Here's an example bash script using node:
cd libs/my-library && json -I -f package.json this.version=$(node -pe \"JSON.stringify(require('../../package.json').version)\")
For my Angular library, I was forced to bump the version in the project package.json
file, the child one not the parent workspace one. So I needed to update the version property in the parent workspace package.json
file.
├── package.json
└── projects
└── lib-pwa
└── package.json
For this I created in the ~/dev/commands/ng.sh
file the bash ng-version-sync-parent
command:
#!/bin/bash
ng-version-sync-parent() {
version=`find ./projects -name package.json -exec cat {} + | jq --raw-output '.version'`;
echo 'Project package version: '$version;
jq --arg version $version ".version = \"$version\"" package.json | sponge package.json
version=`cat package.json | jq --raw-output '.version'`;
echo 'Workspace package version: '$version;
}
I then used it in my workspace directory:
source ~/dev/commands/ng.sh
11:29 $ ng-version-sync-parent
Project package version: 0.1.4
Workspace package version: 0.1.4
I use a combination of sync-json and "pre-post version" scripts to help with this.
npm i -D sync-json
Here's what my package.json
looks like:
{
...,
"scripts": {
"build:lib": "ng build --prod my-lib",
"sync-version": "sync-json -v --property version --source package.json projects/my-lib/package.json",
"preversion": "rm -rf ./dist",
"version": "npm run sync-version && npm run build:lib && git add -A && git commit -m \"bump up\"",
"postversion": "git push && git push --tags"
},
...
}
Just for clarity:
- "sync-version": copies the version from the main package.json and pastes it to the lib package.json
- "prevention": cleans the workspace
- "version": syncs versions, builds lib, commits changes
- "postversion": git push everything