update package.json version automatically

Gitnode.jsNpmGithooks

Git Problem Overview


Before I do a small release and tag it, I'd like to update the package.json to reflect the new version of the program.

Is there a way to edit the file package.json automatically?

Would using a git pre-release hook help?

Git Solutions


Solution 1 - Git

Right answer

To do so, just npm version patch =)

My old answer

There is no pre-release hook originally in git. At least, man githooks does not show it.

If you're using git-extra (https://github.com/visionmedia/git-extras), for instance, you can use a pre-release hook which is implemented by it, as you can see at https://github.com/visionmedia/git-extras/blob/master/bin/git-release. It is needed only a .git/hook/pre-release.sh executable file which edits your package.json file. Committing, pushing and tagging will be done by the git release command.

If you're not using any extension for git, you can write a shell script (I'll name it git-release.sh) and than you can alias it to git release with something like:

git config --global alias.release '!sh path/to/pre-release.sh $1'

You can, than, use git release 0.4 which will execute path/to/pre-release.sh 0.4. Your script can edit package.json, create the tag and push it to the server.

Solution 2 - Git

npm version is probably the correct answer. Just to give an alternative I recommend grunt-bump. It is maintained by one of the guys from angular.js.

Usage:

grunt bump
>> Version bumped to 0.0.2

grunt bump:patch
>> Version bumped to 0.0.3

grunt bump:minor
>> Version bumped to 0.1.0

grunt bump
>> Version bumped to 0.1.1

grunt bump:major
>> Version bumped to 1.0.0

If you're using grunt anyway it might be the simplest solution.

Solution 3 - Git

This is what I normally do with my projects:

npm version patch
git add *;
git commit -m "Commit message"
git push
npm publish

The first line, npm version patch, will increase the patch version by 1 (x.x.1 to x.x.2) in package.json. Then you add all files -- including package.json which at that point has been modified. Then, the usual git commit and git push, and finally npm publish to publish the module.

I hope this makes sense...

Merc.

Solution 4 - Git

As an addition to npm version you can use the --no-git-tag-version flag if you want a version bump but no tag or a new commit:

npm --no-git-tag-version version patch

https://docs.npmjs.com/cli/version

Solution 5 - Git

To give a more up-to-date approach.

package.json

  "scripts": {
    "eslint": "eslint index.js",
    "pretest": "npm install",
    "test": "npm run eslint",
    "preversion": "npm run test",
    "version": "",
    "postversion": "git push && git push --tags && npm publish"
  }

Then you run it:

npm version minor --force -m "Some message to commit"

Which will:

  1. ... run tests ...

  2. change your package.json to a next minor version (e.g: 1.8.1 to 1.9.0)

  3. push your changes

  4. create a new git tag release and

  5. publish your npm package.

--force is to show who is the boss! Jokes aside see https://github.com/npm/npm/issues/8620

Solution 6 - Git

If you are using yarn you can use

yarn version patch

This will increment package.json version by patch (0.0.x), commit, and tag it with format v0.0.0

Likewise you can bump minor or major version by using --minor or --major

When pushing to git ensure you also push the tags with --follow-tags

git push --follow-tags

You can also create a script for it

    "release-it": "yarn version --patch && git push --follow-tags"

Simply run it by typing yarn release-it

Solution 7 - Git

I am using husky and git-branch-is:

As of husky v1+:

// package.json
{
  "husky": {
    "hooks": {
      "post-merge": "(git-branch-is master && npm version minor || 
  (git-branch-is dev && npm --no-git-tag-version version patch)",
    }
  }
}

Prior to husky V1:

"scripts": {
  ...
  "postmerge": "(git-branch-is master && npm version minor || 
  (git-branch-is dev && npm --no-git-tag-version version patch)",
  ...
},

Read more about npm version

Webpack or Vue.js

If you are using webpack or Vue.js, you can display this in the UI using Auto inject version - Webpack plugin

NUXT

In nuxt.config.js:

var WebpackAutoInject = require('webpack-auto-inject-version');

module.exports = {
  build: {
    plugins: [
      new WebpackAutoInject({
        // options
        // example:
        components: {
          InjectAsComment: false
        },
      }),
    ]
  },
}

Inside your template for example in the footer:

<p> All rights reserved © 2018 [v[AIV]{version}[/AIV]]</p>

Solution 8 - Git

First, you need to understand the rules for upgrading the versioning number. You can read more about the semantic version here.

Each version will have x.y.z version where it defines for different purpose as shown below.

  1. x - major, up this when you have major changes and it is huge discrepancy of changes occurred.
  2. y - minor, up this when you have new functionality or enhancement occurred.
  3. z - patch, up this when you have bugs fixed or revert changes on earlier version.

To run the scripts, you can define it in your package.json.

"script": {
    "buildmajor": "npm version major && ng build --prod",
    "buildminor": "npm version minor && ng build --prod",
    "buildpatch": "npm version patch && ng build --prod"
}

In your terminal, you just need to npm run accordingly to your needs like

npm run buildpatch

If run it in git repo, the default git-tag-version is true and if you do not wish to do so, you can add below command into your scripts:

--no-git-tag-version

for eg: "npm --no-git-tag-version version major && ng build --prod"

Solution 9 - Git

I want to add some clarity to the answers this question got.

Even thought there are some answers here that are tackling properly the problem and providing a solution, they are not the correct ones. The correct answer to this question is to use npm version

> Is there a way to edit the file package.json automatically?

Yes, what you can do to make this happen is to run the npm version command when needed, you can read more about it here npm version, but the base usage would be npm version patch and it would add the 3rd digit order on your package.json version (1.0.X)

> Would using a git pre-release hook help?

You could configure to run the npm version command on the pre-release hook, as you need, but that depends if that is what you need or not in your CD/CI pipe, but without the npm version command a git pre-release hook can't do anything "easily" with the package.json

The reason why npm version is the correct answer is the following:

  1. If the user is using a folder structure in which he has a package.json he is using npm if he is using npm he has access to the npm scripts.
  2. If he has access to npm scripts he has access to the npm version command.
  3. Using this command he doesn't need to install anything more in his computer or CD/CI pipe which on the long term will reduce the maintainability effort for the project, and will help with the setup

The other answers in which other tools are proposed are incorrect.

gulp-bump works but requires another extra package which could create issues in the long term (point 3 of my answer)

grunt-bump works but requires another extra package which could create issues in the long term (point 3 of my answer)

Solution 10 - Git

You can use the version-select package:

npm i -D version-select
{
    "name": "test",
    "version": "1.0.0",
    "scripts": {
        "version-select": "version-select"
    },
    "devDependencies": {
        "version-select": "^1.0.13"
    }
}

enter image description here

Read more

Solution 11 - Git

Just in case if you want to do this using an npm package semver link

let fs = require('fs');
let semver = require('semver');

if (fs.existsSync('./package.json')) {
	var package = require('./package.json');
	let currentVersion = package.version;
	let type = process.argv[2];
	if (!['major', 'minor', 'patch'].includes(type)) {
		type = 'patch';
	}

	let newVersion = semver.inc(package.version, type);
	package.version = newVersion;
	fs.writeFileSync('./package.json', JSON.stringify(package, null, 2));

	console.log('Version updated', currentVersion, '=>', newVersion);
}

package.json should look like,

{
  "name": "versioning",
  "version": "0.0.0",
  "description": "Update version in package.json using npm script",
  "main": "version.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "version": "node version.js"
  },
  "author": "Bhadresh Arya",
  "license": "ISC",
  "dependencies": {
    "semver": "^7.3.2"
  }
}

just pass major, minor, patch argument with npm run version. Default will be patch.

example: npm run version or npm run verison patch or npm run verison minor or npm run version major

Git Repo

Solution 12 - Git

With Husky:

{
  "name": "demo-project",
  "version": "0.0.3",
  "husky": {
    "hooks": {
      "pre-commit": "npm --no-git-tag-version version patch && git add ."
    }
  }
}

Solution 13 - Git

I have created a tool that can accomplish automatic semantic versioning based on the tags in commit messages, known as change types. This closely follows the Angular Commit Message Convention along with the Semantic Versioning Specification.

You could use this tool to automatically change the version in the package.json using the npm CLI (this is described here).

In addition, it can create a changelog from these commits and also has a menu (with a spell checker for commit messages) for creating commits based on the change type. I highly recommend checking it out and reading to docs to see everything that can be accomplished with it.

I wrote the tool because I couldn't find anything that suited my needs for my CICD Pipeline to automate semantic versioning. I'd rather focus on what the actual changes are than what the version should be and that's where my tool saves the day.

For more information on the rationale for the tool, please see this.

Solution 14 - Git

I know it is an old question, but I hope this approach can help someone in case you want to automatically update two package.json in a different location in order to use the same version.

First of all, add these lines to your main pakcage.json scripts section:

"new-version": "npm version --git-tag-version=false",
"version": "echo 'starting postversion script'",
"postversion": "LAST_VERSION=$(npm pkg get version | sed 's/\"//g') && echo $LAST_VERSION && cd projects/ngx-timeline && sed -i.bak \"s/\\\"version\\\": \\\"[0-9]\\.[0-9]\\.[0-9]\\\"/\\\"version\\\": \\\"$LAST_VERSION\\\"/g\" package.json && rm package.json.bak && git commit -am \"Release $LAST_VERSION\" && git tag v$LAST_VERSION"

Then running for instance npm run new-version minor,

  1. the first script will run the npm version with the minor and the option to avoid the tag

  2. the version script will run the command you need after the default ones ( in my case just an echo )

  3. In the postversion script with a sed I can override the version in my child package.json, amend the commit (the version script created already one commit by default) and then create a tag.

Solution 15 - Git

Please check my NodeAutoVersionPush macro script. It's a macro using Visual Studio Code API to auto set the new version then do commit and push with a keyboard shortcut.

The new version is based on current date and total commits. But you can easily tweak the code to your preference or for any other language.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontUrG0nView Question on Stackoverflow
Solution 1 - GitgustavotkgView Answer on Stackoverflow
Solution 2 - GitzemircoView Answer on Stackoverflow
Solution 3 - GitMercView Answer on Stackoverflow
Solution 4 - GitTiemeView Answer on Stackoverflow
Solution 5 - GitJonatas WalkerView Answer on Stackoverflow
Solution 6 - GitEric KimView Answer on Stackoverflow
Solution 7 - GitAnima-t3dView Answer on Stackoverflow
Solution 8 - GitMnemoView Answer on Stackoverflow
Solution 9 - GitAlejandro ValesView Answer on Stackoverflow
Solution 10 - GitDmitry GrinkoView Answer on Stackoverflow
Solution 11 - GitBhadresh AryaView Answer on Stackoverflow
Solution 12 - GitDuc Trung MaiView Answer on Stackoverflow
Solution 13 - GitDaniel EagleView Answer on Stackoverflow
Solution 14 - GitEmanuele FricanoView Answer on Stackoverflow
Solution 15 - GitM. SherbeenyView Answer on Stackoverflow