To use caching in a GitHub Actions workflow, you can use the cache action. Here is an example of a workflow that caches the node_modules directory between builds:
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/cache@v2
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- run: npm install
- run: npm test
This workflow is triggered by a push event and runs on the ubuntu-latest runner. It consists of four steps:
I added this logic to my personal blog’s github action to cache the node_modules directory between builds. This will save time on the npm install step and reduce the number of requests to the npm registry.
The full workflow is
name: Build For Github
# Don't want to burn my private minutes at this point
on:
push:
branches:
- master
- main
- feature/*
schedule:
# * is a special character in YAML so you have to quote this string
- cron: '30 21 * * 1-6/3'
jobs:
make_website:
name: Generate Website
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/cache@v2
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- uses: actions/setup-node@v2
name: Update node
with:
node-version: '16'
- name: install astro
run: npm install --force
- name: update config
run: |
npm run build
echo > dist/.nojekyll
- name: Deploy 🚀
uses: JamesIves/github-pages-deploy-action@releases/v3
with:
GITHUB_TOKEN: ${{ secrets.MAIN_REPO_TOKEN }}
BRANCH: gh-pages
FOLDER: dist
This .github/workflows/build.yml file defines a workflow that is triggered by either a push event to the master, main, or feature/* branches, or by a schedule that runs every three weeks on weekdays at 21:30.
The workflow consists of a single job named make_website, which has several steps: