Pass Azure Devops $(Build.BuildNumber) to npm task - npm

I want to update the package.json version through azure devops pipeline.
This is the task I used. But it throws error.
- task: Npm#1
displayName: "npm version"
command: "custom"
workingDir: src
verbose: false
customCommand: "version $(Build.BuildNumber)"
How to correctly pass the pipeline build number to npm task.
Thanks in advance.

We can use command npm version <newversion> to update the package.json version. for example, current version is v1.0.1, using command npm version 2.0.0 will update its version to v2.0.0. Please note that the version format must be the same, like major.minor.patch.
In addition, yaml pipeline will set the build numer to be formatted like 20210426.5 by default. If your package.json is not formatted like this, this command npm version $(Build.BuildNumber) will cause issues. You could use UpdateBuildNumber to override the automatically generated build number.
BTW, the following yaml pipeline is for your reference supposed that your package.json is formatted like major.minor.patch. Also you could use custom variables to specify the version number.
pool:
vmImage: ubuntu-latest
steps:
- task: PowerShell#2
inputs:
targetType: 'inline'
script: |
# Write your PowerShell commands here.
Write-Host "Hello World"
git config --global user.email "you#example.com"
git config --global user.name "Your Name"
echo "##vso[build.updatebuildnumber]2.1.0"
- task: Npm#1
inputs:
command: 'custom'
workingDir: ''
customCommand: 'version $(Build.BuildNumber)'

Related

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?
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:
Set Variables in Build Pipeline.
Add the Replace Tokens task.
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:
Update:
You could try to use the Npm Version command.
npm version 0.0.$(build.buildnumber) --no-git-tag-version
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

Trying to cache npm installs between builds on Azure Devops

I'm trying to configure my pipeline to cache npm between builds.
My pipeline.yml looks like this
variables:
npm_config_cache: $(Pipeline.Workspace)/.npm
trigger:
- master
pool:
vmImage: 'ubuntu-latest'
steps:
- task: NodeTool#0
inputs:
versionSpec: '10.x'
displayName: 'Install Node.js'
- task: Cache#2
inputs:
key: 'npm | "$(Agent.OS)" | package-lock.json'
path: '$(npm_config_cache)'
cacheHitVar: 'CACHE_RESTORED'
restoreKeys: 'npm | "$(Agent.OS)"'
displayName: 'Cache npm'
- task: Npm#1
condition: ne(variables.CACHE_RESTORED, 'true')
inputs:
command: 'install'
- task: Npm#1
inputs:
command: 'custom'
customCommand: 'run lint'
displayName: 'Lint checking'
This works fine up until the npm run lint and then it fails.
However the cache key is found and the cache is restored.
The condition line evaluates to false which is also correct.
If I force the npm install then the lint line works.
Any ideas what the difference between restoring the cache and forcing an npm install would be?
Or any ideas of how else to get this to work?
Thanks for the tip - I should have been way more specific.
Basically this doesn't work for anyone else who is trying this.
This isn't the way to cache npm install :) There just doesn't seem to be a good way to do this between builds.
You can cache the .npm folder but that doesn't really speed builds up much if at all - probably due to Azure caching npm registries and high network speeds internal to Azure
Your question is a bit vague, so I got a suggestion. Look at the variables of your pipeline. See the system.debug variable ? Set it to true. Now, Azure will show usually much more info about what happens in your pipeline. If the linting fails, maybe you find more information. Now adjust your question with the new found diagnostics at hand here.

How to configure ESLint Settings in Azure DevOps YAML?

I'm learning how to use YAML files in my build pipeline and I need to change eslint settings. Specifically, I'm trying to disable the rule that checks for console statements. I've modified it in my local .eslintrc.js file, but the pipeline doesn't appear to use the settings in that file. Am I going about this the right way?
Here's what I have so far:
trigger:
- master
pool:
vmImage: 'ubuntu-latest'
steps:
- task: NodeTool#0
inputs:
versionSpec: '10.x'
displayName: 'Install Node.js'
- script: |
npm install
npm run build
displayName: 'npm install and build'
You have not added any command to run the linter.
Add an additional command like so in the yaml.
- script: |
npm install
eslint src
npm run build
displayName: 'npm install, lint and build'
Or for better clarity, you can add a custom script in the package.json file, as below
"scripts": {
...
"linter": "eslint src",
...
}
then call it from the yaml.
- script: |
npm install
npm run linter
npm run build
displayName: 'npm install, lint and build'

Install peer dependencies in Azure Pipeline

I want to build npm packages via Azure DevOps. My build pipeline fails because peer dependencies are not installed. Is there a way to install the peer dependencies from the package.json?
Below is my sample azure-pipelines.yml file for building and publishing my npm package.
pool:
name: Azure Pipelines
demands: npm
vmImage: 'ubuntu-latest'
steps:
- task: Npm#1
displayName: 'npm install'
inputs:
verbose: false
- task: Npm#1
displayName: 'npm install project'
inputs:
workingDir: 'projects/my-project'
verbose: false
- task: Npm#1
displayName: 'ng build'
inputs:
command: custom
verbose: false
customCommand: 'run ng build -- --prod'
- task: Npm#1
displayName: 'npm publish'
inputs:
command: publish
workingDir: 'dist/my-project'
verbose: false
publishEndpoint: NPM
condition: contains(variables['Build.SourceBranch'], 'master')
Bonus question: How do I apply a tag when publishing?
For this issue ,first, you need to make sure that the Working folder specified in the npm install task contains target package.json.
Secondly, do all the dependent packages you need to use exist in the public feed? If not, you need to use packages from your Azure Artifacts feed.
In addition, you need to make sure that the dependent packages are specified in your package.json. If everything is ok, can you run successfully locally?
Update:
The automatic install of peer dependencies was explicitly removed with npm 3.
Here is the case you can refer to .

Azure Pipelines "Cache#2" fails with "##[error]The system cannot find the file specified"

I'm using Azure Pipelines with hosted builds to build a web project. Our build times were hitting 10-15 minutes, with most (5-10 minutes) of the time spent doing npm install. To speed this up, I'm trying to use the Cache task (https://learn.microsoft.com/en-us/azure/devops/pipelines/caching/?view=azure-devops).
However, when the auto-added task Post-job: Cache runs, it always errors out with:
##[error]The system cannot find the file specified
The host server is Windows Server 2017.
Here is my entire build YAML
# Node.js with Vue
# Build a Node.js project that uses Vue.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/languages/javascript
trigger:
- develop
pool:
name: Default
variables:
FONTAWESOME_NPM_AUTH_TOKEN: $(FONTAWESOME_NPM_AUTH_TOKEN_VARIABLE)
npm_config_cache: $(Pipeline.Workspace)/.npm
steps:
- task: DutchWorkzToolsAllVariables#1
- task: NodeTool#0
inputs:
versionSpec: '10.x'
displayName: 'Install Node.js'
- task: Cache#2
inputs:
key: 'npm | "$(Agent.OS)" | package-lock.json'
path: $(npm_config_cache)
cacheHitVar: NPM_CACHE_RESTORED
- task: Npm#1
displayName: 'npm install'
inputs:
command: 'install'
condition: ne(variables.NPM_CACHE_RESTORED, 'true')
- task: Npm#1
displayName: 'npm run build'
inputs:
command: 'custom'
customCommand: 'run build'
- task: CopyFiles#2
inputs:
SourceFolder: '$(Build.Repository.LocalPath)\dist'
Contents: '**'
TargetFolder: '$(Build.StagingDirectory)'
CleanTargetFolder: true
- task: PublishBuildArtifacts#1
inputs:
PathtoPublish: '$(Build.ArtifactStagingDirectory)'
ArtifactName: 'drop'
publishLocation: 'Container'
Cache task output:
Starting: Cache
==============================================================================
Task : Cache
Description : Cache files between runs
Version : 2.0.0
Author : Microsoft Corporation
Help : https://aka.ms/pipeline-caching-docs
==============================================================================
Resolving key:
- npm [string]
- "Windows_NT" [string]
- package-lock.json [file] --> F93EFA0B87737CC825F422E1116A9E72DFB5A26F609ADA41CC7F80A039B17299
Resolved to: npm|"Windows_NT"|rbCoKv9PzjbAOWAsH9Pgr3Il2ZhErdZTzV08Qdl3Mz8=
Information, ApplicationInsightsTelemetrySender will correlate events with X-TFS-Session zzzzz
Information, Getting a pipeline cache artifact with one of the following fingerprints:
Information, Fingerprint: `npm|"Windows_NT"|rbCoKv9PzjbAOWAsH9Pgr3Il2ZhErdZTzV08Qdl3Mz8=`
Information, There is a cache miss.
Information, ApplicationInsightsTelemetrySender correlated 1 events with X-TFS-Session zzzzz
Finishing: Cache
Post-job: Cache output:
Starting: Cache
==============================================================================
Task : Cache
Description : Cache files between runs
Version : 2.0.0
Author : Microsoft Corporation
Help : https://aka.ms/pipeline-caching-docs
==============================================================================
Resolving key:
- npm [string]
- "Windows_NT" [string]
- package-lock.json [file] --> 2F208E865E6510DE6EEAA6DB0CB7F87B323386881F42EB63E18ED1C0D88CA84E
Resolved to: npm|"Windows_NT"|OQo0ApWAY09wL/ZLr6fxlRIZ5qcoTrNLUv1k6i6GO9Q=
Information, ApplicationInsightsTelemetrySender will correlate events with X-TFS-Session zzzzz
Information, Getting a pipeline cache artifact with one of the following fingerprints:
Information, Fingerprint: `npm|"Windows_NT"|OQo0ApWAY09wL/ZLr6fxlRIZ5qcoTrNLUv1k6i6GO9Q=`
Information, There is a cache miss.
Information, ApplicationInsightsTelemetrySender correlated 1 events with X-TFS-Session zzzzz
##[error]The system cannot find the file specified
Finishing: Cache
How can I fix my build definition so the caching works?
#Levi Lu-MSFT was right in his comment but there's a gotcha.
#FLabranche has a working solution in his answer but I believe reasoning is not quite right.
The problem
npm install and #Cache task are looking for the npm cache at different locations. Consider the flow when pipeline runs for the first time:
#Cache task: does nothing since there's no cache yet.
npm i (or npm ci) task: installs packages in node_modules/ and updates the npm cache at default location. Default location is ~/.npm on Linux/Mac and %AppData%/npm-cache on Windows. On Linux hosted cloud agent the absolute path will be /home/vsts/.npm.
(... more tasks from your pipeline)
Post-job #Cache task (added implicitly): reads the npm cache found at user-provided location to store it for future reuse. User-provided location is set by the npm_config_cache: $(Pipeline.Workspace)/.npm variable. On Linux hosted cloud agent the absolute path will be /home/vsts/work/1/.npm.
As a result, #Cache task fails with tar: /home/vsts/work/1/.npm: Cannot open: No such file or directory.
Solution
Make npm install and #Cache task use the same npm cache location.
One option suggested by Levi Lu is to update the npm config with npm config set cache $(npm_config_cache) --global but it won't work in the pipeline (at least it didn't work for me in an Azure-hosted Linux agent): Error: EACCES: permission denied, open '/usr/local/etc/npmrc'
npm ci --cache $(npm_config_cache) updates the npm cache location for a single call and it does work in this case. It feels a bit hacky though since --cache option is not even documented on the npm website.
All in all this code worked for me:
variables:
NPM_CACHE_FOLDER: $(Pipeline.Workspace)/.npm
steps:
- task: Cache#2
displayName: Cache npm dependencies
inputs:
key: 'npm | "$(Agent.OS)" | package-lock.json'
restoreKeys: |
npm | "$(Agent.OS)"
npm
path: $(NPM_CACHE_FOLDER)
- script: npm ci --cache $(NPM_CACHE_FOLDER)
displayName: 'Install npm dependencies'
...
You can log into your Windows Server 2017 server and check if the folder $(Pipeline.Workspace)/.npm is created and the dependencies are stored inside.
I copied and tested your yaml. It worked both on local agent(win2019) and cloud agents. You can try to run your pipeline on the cloud agents or other agents with newer system to check if it is the agent that cause this error.
The keys generated with your package-lock.json differ between the two tasks.
It happens when the file is modified. Here, they're modified by your npm install task.
You can use the restoreKeys option when configuring the Cache task to fall back onto the latest cache entry.
And I think you don't need the 'npm install' task.
Could you try replacing this :
- task: Cache#2
inputs:
key: 'npm | "$(Agent.OS)" | package-lock.json'
path: $(npm_config_cache)
cacheHitVar: NPM_CACHE_RESTORED
- task: Npm#1
displayName: 'npm install'
inputs:
command: 'install'
condition: ne(variables.NPM_CACHE_RESTORED, 'true')
By this definition :
- task: Cache#2
inputs:
key: 'npm | "$(Agent.OS)" | package-lock.json'
restoreKeys: |
npm | "$(Agent.OS)"
npm
path: $(npm_config_cache)
displayName: Cache npm
- script: npm ci --cache $(npm_config_cache)
Yesterday, I was able to get it working with no issue at all on a self-hosted machine agent by using this:
- task: Cache#2
inputs:
key: '**/package-lock.json, !**/node_modules/**/package-lock.json, !**/.*/**/package-lock.json'
path: '$(System.DefaultWorkingDirectory)/node_modules'
displayName: 'Cache Node Modules'
Today, trying to work on a hosted agent today and this doesn't cut it at all. Aggh, Back to the grinding board. Anyhow, maybe could work for you on your self-hosted pipeline
This seems to be related to this open issue.
I have resolved the problem by switching the build agent pool to hosted and using windows-latest image.
pool:
vmImage: 'windows-latest'