The Right Way to Automatic Semantic Versioning in npm2024-10-19

Introduction

Semantic versioning is a crucial aspect of package management in npm (Node Package Manager). It helps developers understand the nature of changes in a package and manage dependencies effectively. This post will explore the right way to implement automatic semantic versioning in npm projects.

What is Semantic Versioning?

Semantic Versioning, often abbreviated as SemVer, is a versioning scheme that uses a three-part version number: MAJOR.MINOR.PATCH. Each part has a specific meaning:

The Importance of Automatic Semantic Versioning

Automating the process of semantic versioning offers several benefits:

Implementing Automatic Semantic Versioning in npm

To implement automatic semantic versioning in your npm project, follow these steps:

1. Use Conventional Commits

Adopt the Conventional Commits specification for your commit messages. This standardized format helps automate version increments based on commit types.

2. Install necessary tools

yarn add -D @semantic-release/commit-analyzer @semantic-release/release-notes-generator @semantic-release/changelog @semantic-release/npm @semantic-release/git

3. Configure semantic-release

Create a .releaserc file in your project root:

{
  "branches": ["main"],
  "plugins": [
    "@semantic-release/commit-analyzer",
    "@semantic-release/release-notes-generator",
    "@semantic-release/changelog",
    "@semantic-release/npm",
    "@semantic-release/git"
  ]
}

4. Update package.json

Add a "release" script to your package.json:

{
  "scripts": {
    "release": "semantic-release"
  }
}

5. Set up CI/CD

Configure your CI/CD pipeline to run the release script on successful builds of your main branch.

Take Github Action for example

name: Release
on:
  push:
    branches:
      - main
jobs:
  release:    
    name: release
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - uses: actions/setup-node@v3
      with:
        cache: yarn
        node-version: 20
    - run: yarn install --immutable
    - run: npx semantic-release
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Best Practices

Conclusion

Implementing automatic semantic versioning in npm projects streamlines the release process and ensures consistent, meaningful version numbers. By following these steps and best practices, you can maintain a more organized and professional npm package that other developers can rely on.

Reference

https://semantic-release.gitbook.io/semantic-release