Skip to content

Publish Package to npm #1

Publish Package to npm

Publish Package to npm #1

Workflow file for this run

name: Publish Package to npm
# Trigger this workflow whenever a new release is published
on:
release:
types: [published]
# Grant write permissions to the repository contents so we can push version updates
permissions:
contents: write
jobs:
publish:
runs-on: ubuntu-latest
steps:
# Step 1: Check out the repository’s code at the default branch
# This makes your code available for subsequent steps like installing dependencies and running tests.
- uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
ref: ${{ github.event.repository.default_branch }}
# Step 2: Set up a Node.js environment (Node 20.x) and configure npm to use the official registry
# This ensures we have the right Node.js version and a proper registry URL for installs and publishing.
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
# Step 3: Install dependencies using npm ci
# This ensures a clean, reproducible installation based on package-lock.json.
- name: Install dependencies
run: npm ci
# Step 4: Run your test suite (using the "test" script from package.json)
# If tests fail, the workflow will stop here and not publish a broken version.
# - name: Run tests
# run: npm test
# Step 5: Update package.json to match the release tag
# The release tag (e.g., v1.0.1) is extracted, and npm version sets package.json version accordingly.
# The --no-git-tag-version flag ensures npm doesn't create its own tags.
# This step keeps package.json's version aligned with the release tag you just created.
- name: Update package.json with release tag
run: |
TAG="${{ github.event.release.tag_name }}"
echo "Updating package.json version to $TAG"
npm version "$TAG" --no-git-tag-version
# Step 6: Commit and push the updated package.json and package-lock.json back to the repo
# This ensures your repository always reflects the exact version published.
# We use the GITHUB_TOKEN to authenticate and the granted write permissions to push changes.
- name: Commit and push version update
run: |
TAG="${{ github.event.release.tag_name }}"
git config user.name "github-actions"
git config user.email "[email protected]"
git add package.json package-lock.json
git commit -m "Update package.json to version $TAG"
git push origin ${{ github.event.repository.default_branch }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Step 7: Publish the new version to npm
# The NODE_AUTH_TOKEN is your npm access token stored as a secret.
# npm publish --access public makes the package available to anyone on npm.
- name: Publish to npm
run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}