DEV Community

Darlan Alves
Darlan Alves

Posted on • Edited on

Automatically Publish to npm using GitHub Actions

This is a quick step by step on how to publish a package to NPM automatically using semantic releases. You can read more about semantic release conventions before we continue.

What you will need

  • A publish token from NPM, which you can generate in npmjs.com, in your profile.
  • A token for GitHub API, which you can generate if you go to your Profile > Settings > Developer Settings > Personal access tokens. Using “repo” permissions should be enough. Add more as needed.

Step 1: start a new workflow file

Go to your repository > Actions and create a new action.
Use the link “set up a workflow yourself” to get started

Alt Text

Step 2: add a workflow configuration

Just copy paste this snippet into your new Action text. Then create a commit and save it.

name: release
on:
  push:
    branches:
      - master
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      # - name: Install dependencies and build, if needed
      #   run: npm ci && npm run build
      - name: Semantic Release
        uses: cycjimmy/semantic-release-action@v2.5.0
        env:
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Enter fullscreen mode Exit fullscreen mode

If looks like this, the you’re doing it right:

Alt Text

Step 3: make sure you can publish

Let's check your package.json to make sure you have the configuration to allow a publish command to NPM.

Copy this snippet and change with your repository name:

"repository": {
  "type": "git",
  "url": "https://github.com/user/repo.git"
},
"publishConfig": {
  "access": "public"
},
Enter fullscreen mode Exit fullscreen mode

Step 4: add GitHub and NPM secrets

Go to your project Settings > Secrets and add GH_TOKEN and NPM_TOKEN secrets.

You can add to a repository or to an entire organisation. I use orgs when I have several small packages under the same scope.

Alt Text

And that’s it!

Now you can start pushing to your repository and see it auto-published if everything went as planned.

Any changes to master will trigger a new patch/minor/major change based on your commits.

Top comments (0)