DEV Community

Cover image for Automate NPM Package Publishing with GitHub Actions
PEAKIQ
PEAKIQ

Posted on • Originally published at peakiq.in

Automate NPM Package Publishing with GitHub Actions

Originally published on PEAKIQ

Source: https://www.peakiq.in/blog/how-to-publish-an-npm-package-automatically-with-github-actions


How to Publish an NPM Package Automatically with GitHub Actions

Publishing NPM packages can be a cornerstone of modern development, enabling code reuse and collaboration. However, manually publishing updates can be repetitive, error-prone, and time-consuming. This is where Continuous Integration/Continuous Deployment (CI/CD) shines, and GitHub Actions provides a powerful, integrated solution to automate this process.

At PeakIQ, we advocate for automation to streamline development workflows. This guide will walk you through setting up a GitHub Actions workflow to automatically build, test, and publish your NPM package, ensuring a smooth and secure release process.

Why Automate NPM Package Publishing?

Before diving into the "how," let's quickly recap the compelling reasons to automate your package publishing:

  • Consistency: Every release follows the same steps, reducing human error.
  • Speed: Releases can be deployed much faster without manual intervention.
  • Reliability: Automated tests ensure your package is working correctly before it's published.
  • Security: Sensitive credentials are handled securely via GitHub Secrets, not exposed in your local environment.
  • Developer Experience: Free up developers from mundane release tasks to focus on building features.

Prerequisites

To follow along with this guide, you'll need:

  • A GitHub account and a repository for your NPM package.
  • An NPM account.
  • Basic understanding of Git, GitHub, and NPM.
  • A Node.js project initialized as an NPM package (package.json).

Setting Up Your NPM Project

Ensure your NPM package is ready for publication. This typically involves:

  1. package.json: Make sure it has a name, version, and main entry point.
  2. Build Script (Optional but Recommended): If your package requires compilation (e.g., TypeScript, Babel), include a build script in your package.json's scripts section.
  3. Test Script: A test script is crucial for CI/CD. GitHub Actions will run these tests before publishing.

Here's a minimal package.json example:

{
  "name": "@your-scope/your-package-name",
  "version": "1.0.0",
  "description": "A simple example NPM package.",
  "main": "dist/index.js",
  "scripts": {
    "build": "mkdir -p dist && echo 'console.log(\"Hello from your package!\");' > dist/index.js",
    "test": "echo \"No tests specified, but we passed!\" && exit 0",
    "prepublishOnly": "npm run build"
  },
  "keywords": ["example", "peakiq"],
  "author": "PeakIQ",
  "license": "MIT"
}
Enter fullscreen mode Exit fullscreen mode

Note: For a real project, replace the build and test scripts with your actual build tools and testing frameworks.

Generating an NPM Access Token

For GitHub Actions to publish to NPM, it needs authorization. You'll generate a special token from NPM and store it securely in GitHub.

  1. Log in to NPM: Visit https://www.npmjs.com/ and log in to your account.
  2. Generate a Token: Go to your profile settings -> "Auth Tokens" and click "Generate New Token."
  3. Select "Publish" Role: Choose the "Publish" token type. This grants the token only the necessary permissions to publish packages, minimizing risk.
  4. Copy the Token: Once generated, copy the token immediately. You won't be able to see it again.

Adding the Token to GitHub Secrets

Now, add this token to your GitHub repository as a secret:

  1. Navigate to your GitHub repository.
  2. Go to Settings > Secrets and variables > Actions.
  3. Click New repository secret.
  4. For "Name," enter NPM_TOKEN.
  5. For "Secret," paste the NPM token you copied.
  6. Click Add secret.

This secret will now be securely available to your GitHub Actions workflows.

Creating Your GitHub Actions Workflow

GitHub Actions workflows are defined in YAML files located in the .github/workflows/ directory of your repository.

  1. Create a new directory: .github/workflows/ in the root of your project.
  2. Create a new file inside: publish-package.yml (or any descriptive name).

Here's the complete workflow file:

name: Publish NPM Package

on:
  release:
    types: [published]
  workflow_dispatch:

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18.x' # Or your preferred Node.js version
          registry-url: 'https://registry.npmjs.org/'

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test

      - name: Build package (if applicable)
        run: npm run build
        if: always() # Ensure this runs even if tests fail, or adjust as needed

      - name: Publish to NPM
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: npm publish --access public
Enter fullscreen mode Exit fullscreen mode

Let's break down this workflow:

name

name: Publish NPM Package
Enter fullscreen mode Exit fullscreen mode

A human-readable name for your workflow, visible in the GitHub Actions tab.

on

on:
  release:
    types: [published]
  workflow_dispatch:
Enter fullscreen mode Exit fullscreen mode

This defines when the workflow should run:

  • release: types: [published]: The workflow will trigger automatically whenever a new GitHub Release is published. This is a common and recommended approach for managing package versions and releases.
  • workflow_dispatch: Allows you to manually trigger the workflow from the "Actions" tab in your GitHub repository. Handy for testing or specific scenarios.

jobs

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      # ... steps defined below
Enter fullscreen mode Exit fullscreen mode

A workflow can have one or more jobs. Here, we have a single publish job that runs on an ubuntu-latest virtual machine.

steps

Each job consists of a series of steps executed sequentially.

  1. Checkout repository:

    - name: Checkout repository
      uses: actions/checkout@v4
    

    This step uses the actions/checkout action to clone your repository's code onto the runner, making it available for subsequent steps.

  2. Set up Node.js:

    - name: Set up Node.js
      uses: actions/setup-node@v4
      with:
        node-version: '18.x'
        registry-url: 'https://registry.npmjs.org/'
    

    The actions/setup-node action sets up the specified Node.js version and configures NPM to use the official registry. Crucially, the registry-url option, combined with NODE_AUTH_TOKEN in the publish step, tells NPM where to publish and how to authenticate.

  3. Install dependencies:

    - name: Install dependencies
      run: npm ci
    

    npm ci (clean install) is preferred over npm install in CI environments because it strictly installs dependencies based on package-lock.json, ensuring consistent builds.

  4. Run tests:

Top comments (0)