Skip to content

Instantly share code, notes, and snippets.

Last active May 27, 2021 21:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aredridel/8973e96b4ff60fd98716 to your computer and use it in GitHub Desktop.
Save aredridel/8973e96b4ff60fd98716 to your computer and use it in GitHub Desktop.
How to use npm version lifecycle scripts to make sure that publishes make it back to git

The problem

you bump the version of your package and publish to npm; the new version rolls out to users. However, you never make a tag, or forget to push it to github, so there's no record outside of npm that this has happened.

A solution using npm version lifecycle scripts

Add a script like this to your package.json:

"postversion": "git push origin master --follow-tags && npm publish"

Then you can make a release with a command as simple as this:

npm version minor

to make a new minor release, and similarly for major and patch versions.

You can also hook the lifecycle scripts in the pre script to run tests:

"preversion": "npm install && npm test"

And that will abort the version bump if your tests don't pass. What will happen then is this:

  1. npm will see the preversion lifecycle script, and will run npm install, and if that's successful, it will be followed by npm test.
  2. If that is successful, then npm will bump the version number in package.json in the way you specified (major, minor, patch, etc. Read the documentation for npm version for specifics). Along with that, npm will see that this is a git repository and run the git tag command to create a tag for that version and commit it if your working tree is clean.
  3. npm will see the postversion lifecycle script, and will run git push origin master --follow-tags, which will push the version bump to your origin repository's master branch, and any tags that were not yet pushed, including the new one. Finally, if that succeeds, npm will run npm publish to push the new version to the registry. This is last because npm publish is not an action that can be rolled back and tried again.

Another way to go

Check out the semantic-release package, which offers a different way to go about this and solving the same kind of problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment