I am using GitHub Actions to build my TypeScript project. Everytime I run action I am waiting 3 minutes for all dependencies to get installed.
Is there way to cache
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
The caching code above only caches and restores the yarn cache directory, it doesn't cache the node_modules directory. So if you use this code (@Edric's answer),
- name: Install project dependencies
if: steps.yarn-cache.outputs.cache-hit != 'true' # Over here!
run: yarn
node_modules is not created and you will receive dependencies not found errors.
Instead, you can use this:
- name: Install project dependencies
run: yarn --prefer-offline
This tells yarn to always run but use cached downloads (in the cache directory mentioned above) whenever possible instead of downloading from the server.
You can also cache the node_modules directory directly and skip the installation step when the cache is available. This is actually NOT recommended (see comments). Example:
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Cache yarn cache
uses: actions/cache@v2
id: cache-yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Cache node_modules
id: cache-node-modules
uses: actions/cache@v2
with:
path: node_modules
key: ${{ runner.os }}-${{ matrix.node-version }}-nodemodules-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-${{ matrix.node-version }}-nodemodules-
- run: yarn
if: |
steps.cache-yarn-cache.outputs.cache-hit != 'true' ||
steps.cache-node-modules.outputs.cache-hit != 'true'