Github Actions: cache yarn install

Edited : Upgraded actions/setup-node to version 2.

Caching dependencies installed by Yarn in Github Actions is fairly straightforward, but there are a few small gotchas to get right:

Combining the above with the examples from the documentation, below is a functional example of a Github Action with dependency caching.

name: Descriptive Name

# Update to match your requirements
on: push

jobs:
  descriptive-name:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [12.x]

    steps:
    - uses: actions/checkout@v2

    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.node-version }}

    # See: https://github.com/actions/cache/blob/main/examples.md#node---yarn
    - name: Get Yarn cache directory
      id: yarn-cache-dir-path
      run: echo "::set-output name=dir::$(yarn cache dir)"

    - name: Use Yarn cache
      uses: actions/cache@v2
      id: yarn-cache
      with:
        path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
        key: ${{ runner.os }}-yarn-${{ matrix.node-version }}-${{ hashFiles('**/yarn.lock') }}

    # `--prefer-offline` gives cache priority
    - name: Install dependencies
      run: yarn install --prefer-offline --frozen-lockfile

    # Ready to run steps that rely on node_modules
    # - name: Build application
    #   run: yarn build