Skip to content

Instantly share code, notes, and snippets.

@rupeshtiwari
Created March 30, 2021 15:01
Show Gist options
  • Save rupeshtiwari/44ebec690f2c01bf1df9b1d215a0e723 to your computer and use it in GitHub Desktop.
Save rupeshtiwari/44ebec690f2c01bf1df9b1d215a0e723 to your computer and use it in GitHub Desktop.
cache node_modules in github workflow
name: Caching npm packages
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Cache node modules
id: cache-nodemodules
uses: actions/cache@v2
env:
cache-name: cache-node-modules
with:
# caching node_modules
path: node_modules
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-
${{ runner.os }}-build-
${{ runner.os }}-
- name: Install Dependencies
if: steps.cache-nodemodules.outputs.cache-hit != 'true'
run: npm ci
- name: Build
run: npm build
@nicktalb
Copy link

nicktalb commented Jun 7, 2023

The example works well if the primary key has a cache hit and npm ci is skipped. I would remove restore-keys though. Running npm ci will remove any node_modules folder. If there is a cache entry that matches restore-keys but not key, GitHub will restore it, but then cache-hit will be false and npm ci will immediately delete the restored cache before installing dependencies from scratch. A minor thing but will save some redundant work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment