Release NPM Package With Automatic Versioning

// #devops#javascript#node#npm // 2 comments

I know there are many ways to automate the package release workflow, but sometimes all you need is a simple one line script that takes care of versioning and publishing.

{ "name": "my-awesome-package", "version": "1.0.0", "scripts": { "release": "npm version $(semver $npm_package_version -i minor) && npm publish --tag latest", }, "devDependencies": { "semver": "^7.3.7" } }

This release script increments the version number of the package and publishes the package to the NPM registry (or other registry). To correctly increment the version number, npm's semver package automatically finds the next version number according to the specified level minor (major/minor/patch).

One can, of course, create three scripts for each semver level major, minor, and patch:

{ "name": "my-awesome-package", "version": "1.0.0", "scripts": { "release:major": "npm version $(semver $npm_package_version -i major) && npm publish --tag latest", "release:minor": "npm version $(semver $npm_package_version -i minor) && npm publish --tag latest", "release:patch": "npm version $(semver $npm_package_version -i patch) && npm publish --tag latest" }, "devDependencies": { "semver": "^7.3.7" } }

Pre-release Package With User Suffix

If you are working in a team and need to release a package to test it in another project, you may want to release that package as an alpha or beta version first to avoid your colleagues accidentally installing the latest update. This intermediate version is called prerelease, like 1.0.0-1. Of course, this version could still clash with an existing version from another teammate. To make the version truly unique, we can append the username to the version suffix. This results in version numbers like 1.0.1-zirkelc.1 with zirkelc as the username.

{ "name": "my-awesome-package", "version": "1.0.0", "scripts": { "release:beta": "npm version $(semver $npm_package_version -i prerelease --preid $(npm whoami) ) && npm publish --tag beta", }, "devDependencies": { "semver": "^7.3.7" } }

The command npm whoami returns the npm username of the currently logged-in user. This works also with private registries like GitHub Registry. The flag --tag beta is required because npm publishes packages with latest tag by default. To install this prerelease version in another package, the command npm install my-awesome-package@beta must be executed with the tag beta instead of latest (default tag if omitted).