Published on

Auto Publish NPM Package when package.json version changes

Authors

Recently, for fun, I've started working on a npm package where I can dump all my helper functions so that I can just focus on coding something instead of figuring out how to do something over and over again.

I'm building that package just for me. So I don't have to worry about frequent publishing.

Now that it's in the early phase, I'm making so many changes to it, and it was really hard to publish the package to npm again and again.

So I've decided to automate that using GitHub Action. There were a lot of existing GitHub actions which required me to follow some practice like having a commit message with a "Release x.x.x" pattern or something like that and I don't want to follow something like that for a fun project.

Surprisingly it's straightforward to build our own. In this example, I'll be using GitHub Action but you can do a similar workflow in your CI as well.

Whenever there is a change in the version field package.json file, it'll auto-publish the package to npm.

Auto Publish NPM using GitHub Action

Dependency

Make sure to configure NPM_TOKEN which has write access for your GitHub Action.

You can configure it under your repo's settings.

Workflow Snippet

And place your file under .github/workflows directory.

Something like: github/workflows/auto-publish-npm.yml

name: Publish to NPM

on:
  push:
    branches:
      - main

jobs:
  publish:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v2

    - name: Setup Node.js
      uses: actions/setup-node@v4
      with:
        node-version: 18
        # https://github.com/actions/setup-node#caching-global-packages-data
        cache: 'npm'

    - name: Install dependencies
      run: npm install

    - name: Get previous commit version
      id: prev_version
      run: echo "::set-output name=version::$(git show ${GITHUB_SHA}^:package.json | jq -r .version)"

    - name: Get current commit version
      id: current_version
      run: echo "::set-output name=version::$(jq -r .version package.json)"

    - name: Check for version change
      run: |
        if [ "${{ steps.prev_version.outputs.version }}" != "${{ steps.current_version.outputs.version }}" ]; then
          echo "Package version has changed. Proceeding with build and publish."
        else
          echo "No changes to package version. Skipping build and publish."
          exit 78
        fi

    - name: Build
      run: npm run build

    - name: Set up NPM authentication
      run: echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > ~/.npmrc
      env:
        NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

    - name: Publish to NPM
      run: npm publish

And that's pretty much it.

Happy auto-publishing packages!