Douglas Moura

Douglas Moura

Software Engineer
Douglas Moura

Douglas Moura

I write about TypeScript, React and Node.js.

Use GitHub actions to publish your package on NPM

Published at:Published at:Updated at:
Use GitHub actions to publish your package on NPM

Recently, I created a package with the ESLint settings I like to use in my React projects, as I was tired of always having to configure it when I start new React projects. Publishing a NPM package is just a matter of running npm publish on the directory of your package (considering, of course, that you already have an NPM account and is authenticated on your terminal). But I wanted to automatize this publishing everytime I created a new release.

In order to do that, I used the following GitHub Action:

1
# File: .github/workflows/npm-publish.yml
2
3
# This workflow will publish a package to NPM when a release is created
4
# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages
5
6
name: Publish Package to npmjs
7
8
on:
9
release:
10
types: [created]
11
12
jobs:
13
build:
14
runs-on: ubuntu-latest
15
steps:
16
- uses: actions/checkout@v3
17
- uses: actions/setup-node@v3
18
with:
19
node-version: 16
20
registry-url: https://registry.npmjs.org/
21
- run: npm publish
22
env:
23
NODE_AUTH_TOKEN: ${{secrets.NODE_AUTH_TOKEN}}

If you read the YAML file above (that you should put on the .github/workflows/npm-publish.yml directory of your git repository), you should have noted that the environment variable NODE_AUTH_TOKEN should be defined. Create a new automation access token on the control panel of NPM:

  1. Access your NPM account and click in "Access tokens": Access tokens on NPM

  2. Name your new access token and select the "Automation" type for it:

Creating access token on NPM

  1. Go to your GitHub repository, click in "Settings > Secrets > Actions > New repository secret", name it as NODE_AUTH_TOKEN and paste the access token you just got from NPM:

Create a new secret on the GitHub repository

  1. Create a new release for your package. This should trigger our GitHub Action and publish to NPM.

Creating a new release on GitHub

Leave a Reply

Loading comments...