During our last retrospective, one of the complaints was that the build time was too long. We were using the Hosted Build Services on Azure and restoring the NPM packages on every build took way too long.
Fortunately, Azure DevOps now offers a new build task called cache task. This task will restore the cached data based on the provided inputs. Let’s see how we can use this task to cache our NPM packages:
- Add the cache task to your build steps
- Now we first need to set a cache key. The cache key is be used as the identifier for the cache and can be a combination of string values, file paths and file patterns. In our case we want to use the package-lock.json file as the key. Every time the package-lock.json changes the cache will be invalidated and the npm packages will be restored again.
- **/package-lock.json, !**/node_modules/**/package-lock.json, !**/.*/**/package-lock.json
- The second thing we need to set is the directory to populate the cache from and restore back to. As we want to cache the npm packages we cache the ‘node_modules’ folder:
- $(System.DefaultWorkingDirectory)/Bridges.CMS.SPA/node_modules
Now if we build again, the first time the cache is populated and the second time we win a lot of time as the node_modules folder is restored from the cache. Yippie!