GitHub actions to publish npm packages

Build, test and deploy npm packages with GitHub actions.

GitHub actions allow you to run scripts for your repository without having to use applications. This is my early exploration of what is possible with GitHub actions and npm. There are heaps of alternatives, so make sure to try them out!

To follow along you will need to sign up to the GitHub actions beta.

Publishing workflow

I have some npm packages with specific workflow I always follow before deploying a new version. My usual workflow for publishing npm packages is to:

  1. Create a Pull Request into main
  2. Merge the pull request into main
  3. Checkout main branch locally
  4. Install dependencies npm install
  5. Test the functionality npm run test
  6. Publish the package to the npm registry npm publish
  7. If any of these steps fail I don't want to publish the package

With GitHub actions I can change the workflow to:

  1. Create a Pull Request into any branch
  2. Run GitHub actions
  3. If any of the actions fail I will get failed checks in the Pull Request
  4. Merge the pull request

Create a main.workflow

To use GitHub actions you need to create a .github/main.workflow file in your main branch. This file tells GitHub you have a workflow to run. You can do this by creating the file in your repository or clicking the actions tab in GitHub.

Workflow

Once you have the file created we need to add a workflow. To create workflow we need:

A push event is ran when a push to a repository branch is made. Branch pushes and repository tag pushes also trigger webhook push events.

					
					
				

Screenshot of how to create a workflow in the GitHub user interface

Actions

Now that we have a workflow created we can create our actions. Actions are docker containers that use arguments, secrets and environment variables with the files in your repository. To create an action for publish we need:

					
					
				

Note: you will need the word run before custom npm scripts.

We now have a new workflow that runs for every push into the repository. It will create a docker container using actions/npm@main and run npm install then npm run test. If the install and test pass the workflow resolves successfully.

Publishing when pushed to main

Lets add some more actions for install, test and filtering for the main branch. We will use the actions/bin/filter@main to make sure we are in the main branch before running the publish action. The publish action will need a secret NPM_AUTH_TOKEN to publish to the NPM registry, you can create an npm token here.

Lets update our workflow to include filtering and publishing.

					
					
				

And thats it! You now have a simple workflow to publish your npm packages.

If you liked this post or have feedback please let me know. I am thinking of writing some more posts on publishing static sites and a beginners guide to creating an action.