BlueCaret
BlueCaret

Reputation: 5020

Automatically bump package.json version on a monorepo setup

I have an Angular 6 app setup as a monorepo with a project that needs to be published to NPM and a demo app. I want to bump the version for both the app, and the project using npm version.

My structure is like this:

| MyFolder/
| -- package.json   <= "Demo App" package file
| -- src/
| -- projects/
     | -- mylibrary/
          | -- package.json   <= My Angular Library package file

When I run npm version on MyFolder root, it only updates the version number for the Demo App, instead I want it to update both the Demo App and the Library's package.json files with the new version.

I know I can just run the npm version command twice, but I'd rather make it all one step to avoid forgetting to do one or the other.

Is there a way I can make this update multiple package.json files with a single command?

Upvotes: 2

Views: 2391

Answers (1)

pascalpuetz
pascalpuetz

Reputation: 5418

I am using a small nodejs Script to achieve that.

const mainPackageJson = require('../package.json');
const glob = require('glob');
const fs = require('fs');

glob.sync('./projects/**/package.json')
   .forEach(location =>
      fs.writeFileSync(location, JSON.stringify({
         ...JSON.parse(fs.readFileSync(location)),
         version: mainPackageJson.version
      }, null, 3))
   );

I'm calling this script during the "version" script in package.json. This gets executed after npm set the new version but before commiting to git. Afterwards, I'm adding the files to git (you don't need to commit since npm will take care of that):

package.json:

{
   "name": "my-name",
   "version": "1.0.0",
   "scripts": {
      "version": "run-s version:bump-all version:add-all",
      "version:bump-all": "node ./build_utils/bump-version.js",
      "version:add-all": "git add \"*/package.json\"",
   },
   "devDependencies": {
      "npm-run-all": "^4.1.3",
      "glob": "^7.1.3",
   }
}

Note that I'm using "glob" library to get the package.json files in sub folders through a glob pattern. Additionally, I'm using npm-run-all to avoid the usage of "&&" to chain commands in package.json scripts (run-s is from npm-run-all and runs 2 commands sequentially)

Upvotes: 6

Related Questions