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:
-
package.json: Make sure it has aname,version, andmainentry point. - Build Script (Optional but Recommended): If your package requires compilation (e.g., TypeScript, Babel), include a
buildscript in yourpackage.json'sscriptssection. - Test Script: A
testscript 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"
}
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.
- Log in to NPM: Visit https://www.npmjs.com/ and log in to your account.
- Generate a Token: Go to your profile settings -> "Auth Tokens" and click "Generate New Token."
- Select "Publish" Role: Choose the "Publish" token type. This grants the token only the necessary permissions to publish packages, minimizing risk.
- 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:
- Navigate to your GitHub repository.
- Go to Settings > Secrets and variables > Actions.
- Click New repository secret.
- For "Name," enter
NPM_TOKEN. - For "Secret," paste the NPM token you copied.
- 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.
- Create a new directory:
.github/workflows/in the root of your project. - 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
Let's break down this workflow:
name
name: Publish NPM Package
A human-readable name for your workflow, visible in the GitHub Actions tab.
on
on:
release:
types: [published]
workflow_dispatch:
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
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.
-
Checkout repository:
- name: Checkout repository uses: actions/checkout@v4This step uses the
actions/checkoutaction to clone your repository's code onto the runner, making it available for subsequent steps. -
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-nodeaction sets up the specified Node.js version and configures NPM to use the official registry. Crucially, theregistry-urloption, combined withNODE_AUTH_TOKENin the publish step, tells NPM where to publish and how to authenticate. -
Install dependencies:
- name: Install dependencies run: npm cinpm ci(clean install) is preferred overnpm installin CI environments because it strictly installs dependencies based onpackage-lock.json, ensuring consistent builds. Run tests:
Top comments (0)