How to Cache Build Dependencies in Azure Pipelines
The Cache@2 task restores a directory keyed on your lockfile hash, so unchanged dependencies are not reinstalled.
Add a Cache@2 step before install. Build the key from a lockfile hash so it busts only when dependencies change, and add restoreKeys for partial hits.
Cache the npm store
The key hashes package-lock.json; restoreKeys gives a fallback when the exact key misses.
azure-pipelines.yml
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)
- script: npm ciGotchas
- Point npm at a cache directory you control (
npm_config_cache); cachingnode_modulesdirectly is fragile across OSes. - The cache is saved only when the job succeeds and the key did not already exist.
- Quote
"$(Agent.OS)"in the key so Windows and Linux do not share an incompatible cache.
Related guides
How to Publish and Download Pipeline Artifacts in Azure PipelinesPass files between jobs and stages in Azure Pipelines with PublishPipelineArtifact and DownloadPipelineArtifa…
How to Define Stages and Jobs in Azure PipelinesStructure an Azure Pipeline with stages, jobs, and steps. Learn the hierarchy, dependsOn ordering, and when e…