Skip to content

Instantly share code, notes, and snippets.

@rupeshtiwari
Created March 30, 2021 15:01
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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
@C0ZEN
Copy link

C0ZEN commented Nov 13, 2021

I was misled by https://github.com/actions/cache/blob/main/examples.md#macos-and-ubuntu, using path: ~/.npm.
Thank you!

@binwiederhier
Copy link

binwiederhier commented May 31, 2022

This is indeed working wonderfully. Not sure why the official docs talk about ~/.npm

@johnico
Copy link

johnico commented Jun 26, 2022

amazing thanks
@rupeshtiwari
is there any option to use the cache also only if the version property has been changed in package.lock? using npm version prerelease for example

@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