How to cache node_modules on Github Actions
tl;dr
- Github will charge you by execution time, so apply this feature will reduce your invoice.
- This post shows a way to cache the
node_modules
during a Github Action execution. - The benefits of ovoid the
npm ci
step can speed up the action execution.
Most of the Github Actions I've created are Node.js apps, so the npm install
is always part of the requirements. I found this way to reduce the execution time by using the actions/cache@v2
cache action.
Just ovoid the npm ci
entire action when the package-lock.json
doesn't change.
- name: Cache dependencies
id: cache
uses: actions/cache@v2
with:
path: ./node_modules
key: modules-${{ hashFiles('package-lock.json') }}
- name: Install dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: npm ci
So this is the example of the Github Actions using cache.
name: CI
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '16'
- name: Cache dependencies
id: cache
uses: actions/cache@v2
with:
path: ./node_modules
key: modules-${{ hashFiles('package-lock.json') }}
- name: Install dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: npm ci
# ... here all the things related to the job, like test script, lint or deploy
Wrap up
This solution is could work or not for your project, keep in mind is just a way to do it.
The cache will last 7 days in Github, just keep that in mind.
So, let's reduce your Github invoice right now :D.
Happy coding!