Search code examples
npmazure-devopssemantic-versioningazure-artifacts

npm version in Azure DevOps pipeline


I have a build pipeline in Azure DevOps which releases artifact via npm pack for later publishing into Artifacts Feed.

I would like to set my major and minor version via GIT but patch version to tie with build number. E.g.

1.2.20201212.4

where 1 and 2 is major.minor version manually updated via GIT and 20201212.4 is a patch and revision number set by build pipeline

Could someone help me to figure out the required npm version command parameters to preserve minor.major version from source code and update only patch and revision part from $(Build.BuildNumber) variable?


Solution

  • In Azure Devops, you could use the Replace Tokens task from the Replace Tokens Extension.

    Then you could add the task before the NPM pack task to replace the variable in Package.json -> Version field.

    Here are the steps:

    Package.Json file:

    {
      "name": "helloword",
      "version": "0.0.#{SetNumber}#",
      "description": "Hello World",
      "main": "server.js",
    ...
    }
    

    Build Pipeline:

    1. Set Variables in Build Pipeline.

    enter image description here

    1. Add the Replace Tokens task.

    enter image description here

    Note: Based on my test, npm package cannot support xx.x.x.x version format(npm publish) in azure devops. It can support the x.x.x-x.

    So you can set buildnumber like this:$(Date:yyyyMMdd)-$(Rev:r).

    Result:

    enter image description here

    Update:

    You could try to use the Npm Version command.

    npm version  0.0.$(build.buildnumber) --no-git-tag-version
    

    enter image description here

    Update2:

    You could try to use the following powershell script to get the version field in the Package.json. Then update the patch number.

    $filePath = "$(Build.sourcesdirectory)\package.json" #filepath
    $Jsonfile= Get-Content $filePath | ConvertFrom-Json
    $version = $Jsonfile.version
    
    echo $version
    
    $major,$minor,$build = $version.Split('.')    
    
    $build = "$(build.buildnumber)"    
    
    $bumpedVersion = $major,$minor,$build  -join(".")
    
    echo $bumpedVersion
    
    Write-Host "##vso[task.setvariable variable=version]$bumpedVersion"
    

    In Npm version, you could run the following command:

    version $(version) --no-git-tag-version
    

    enter image description here