Last Updated: February 25, 2016
·
3.372K
· sebastianhoitz

Easy version publishing to npm via Makefile

Our team uses a very handy snippet to automatically publish new versions to npm, including git tags etc.

Without further ado, here is the Makefile:

BIN = ./node_modules/.bin
.PHONY: test clean

test:
    @npm test

define release
    VERSION=`node -pe "require('./package.json').version"` && \
    NEXT_VERSION=`node -pe "require('semver').inc(\"$$VERSION\", '$(1)')"` && \
    node -e "\
        var j = require('./package.json');\
        j.version = \"$$NEXT_VERSION\";\
        var s = JSON.stringify(j, null, 2);\
        require('fs').writeFileSync('./package.json', s);" && \
    git commit -m "Version $$NEXT_VERSION" -- package.json && \
    git tag "$$NEXT_VERSION" -m "Version $$NEXT_VERSION"
endef

release-patch: test
    @$(call release,patch)

release-minor: test
    @$(call release,minor)

release-major: test
    @$(call release,major)

publish:
    git push
    git push --tags origin HEAD:master
    npm publish

All you have to do, is add the semver package to your package.jsons devDependencies and install it:

npm install --save-dev semver

Now imagine you are at version 0.1.1 and you call

make release-patch# sets version to 0.1.2
make release-minor# sets version to 0.2.0
make release-major# sets version to 1.0.0

it will also run your unit tests to validate if everything is ok. When this succeeded, you can call

make publish

to publish the package to npm and to push the new version including the version tag to git.

Notice that this can also easily be extended to include bower support, too!