Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NPM Cache Step not working in Azure DevOps

I followed the following doc from Microsoft to configure the npm cache step for android app i am trying to build in azure and instead of package.json-Lock i am using package.json.

https://learn.microsoft.com/en-us/azure/devops/pipelines/release/caching?view=azure-devops#nodejsnpm

I am able to upload the cache dependency file in the post-cache step and upload that file in the beginning correctly when running the pipeline for 2nd time but even after the npm cache data is downloaded in the workspace the npm install step is still calling the remote libraries and downloading the remote dependencies.

I have also tried to run npm install --prefer-offline for the npm install step but did work. Please let me know if i am missing anything more.

Thankyou.

like image 795
sam Avatar asked Feb 05 '26 05:02

sam


2 Answers

Use the Cache task to cache your application's node_modules folder. Use the cache hit variable (cacheHitVar) to store the result of the cache restoration. It will be set to true when the cache is restored (cache hit), otherwise set to false.

Then use a condition for the task that installs your dependencies (e.g. npm ci). Only install them on a cache miss.

steps:
  - task: Cache@2
    displayName: Cache node_modules
    inputs:
      key: 'npm | "$(Agent.OS)" | $(Build.SourcesDirectory)/package-lock.json'
      path: $(Build.SourcesDirectory)/node_modules
      cacheHitVar: CACHE_RESTORED

  - task: Npm@1
    displayName: 'Install the dependencies'
    inputs:
      command: custom
      verbose: false
      customCommand: 'ci'
    condition: ne(variables.CACHE_RESTORED, 'true')

You'll see the following output in the pipeline execution when the cache was restored successfully.

Azure Pipeline Execution

like image 196
Christophe Geers Avatar answered Feb 07 '26 22:02

Christophe Geers


Please check the following official recommendation from Microsoft regarding node modules caching https://learn.microsoft.com/en-us/azure/devops/pipelines/release/caching?view=azure-devops#nodejsnpm

variables:
  npm_config_cache: $(Pipeline.Workspace)/.npm

steps:
- task: Cache@2
  inputs:
    key: 'npm | "$(Agent.OS)" | package-lock.json'
    restoreKeys: |
       npm | "$(Agent.OS)"
    path: $(npm_config_cache)
  displayName: Cache npm

- script: npm ci

Because npm ci deletes the node_modules folder to ensure that a consistent, repeatable set of modules is used, you should avoid caching node_modules when calling npm ci.

like image 30
Nedudi Avatar answered Feb 07 '26 20:02

Nedudi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!