Using caching in workflows
In this recipe, we will use caching to optimize the speed of workflows.
Getting ready
Switch to a new branch:
$ git switch -c cache-npm-packages
How to do it…
- Edit the
.github/workflows/ci.yml
file. After thesetup-node
action, add the following script to get thenpm
cache directory for the correctnpm
version and store it as an output variable:- name: Get npm cache directory id: npm-cache-dir run: echo "dir=$(npm config get cache)" >> "${GITHUB_OUTPUT}"
- Add the actual cache step right after that. Also, give it a name and create a key from the hash of the
package-lock.json
file:- uses: actions/cache@v3 id: npm-cache with: path: ${{ steps.npm-cache-dir.outputs.dir }} key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} restore-keys: | ...