|
| 1 | +--- |
| 2 | +title: "Cache your actions" |
| 3 | +permalink: "/blog/cache-your-actions.html" |
| 4 | +date: 2024-05-06 |
| 5 | +description: | |
| 6 | + If your actions have a long installation step (or very big node_modules) you can cache the installation step using the GitHub action actions/cache |
| 7 | +tags: |
| 8 | + - github-action |
| 9 | +--- |
| 10 | +If your actions have a long installation step (or very big `node_modules`) you can cache the installation step using the GitHub action [`actions/cache`](https://github.com/actions/cache). |
| 11 | + |
| 12 | +This is very useful for cases where you use a [matrix to run multiple tests](../run-all-your-tests-concurrently). |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +They have a lot of [implementation examples](https://github.com/actions/cache/blob/main/examples.md), but they all follow the same logic. |
| 17 | + |
| 18 | +### Find out where your package manager downloads the artifacts |
| 19 | +There are step by step instructions for most popular package manager. For example, you can obtain `npm`’s cache by having the following step: |
| 20 | + |
| 21 | +{% raw %} |
| 22 | +```yaml |
| 23 | +- name: Get npm cache directory |
| 24 | + id: npm-cache-dir |
| 25 | + shell: bash |
| 26 | + run: echo "dir=$(npm config get cache)" >> ${GITHUB_OUTPUT} |
| 27 | +``` |
| 28 | +
|
| 29 | +In the case of this action, the cache gets store into the `steps.npm-cache-dir.outputs.dir` variable. |
| 30 | + |
| 31 | +### Restoring the cache |
| 32 | +After you know where your cache is located, you can restore it by using the `actions/cache` action: |
| 33 | + |
| 34 | +```yaml |
| 35 | +- uses: actions/cache@v4 |
| 36 | + with: |
| 37 | + path: ${{ steps.npm-cache-dir.outputs.dir }} # Cache variable |
| 38 | + key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} |
| 39 | + restore-keys: | |
| 40 | + ${{ runner.os }}-node- |
| 41 | +``` |
| 42 | +{% endraw %} |
| 43 | + |
| 44 | +We only want to restore the cache when the packages changed, so we set the `key` variable to use the hashed `package-lock.json`. |
| 45 | + |
| 46 | +We also don’t want to cache the dependencies for a different OS, so we add to the `key` variable the name of the OS. |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | +And that’s all! Now you can cache all your actions. |
| 51 | + |
| 52 | +Remember to [checkout the examples for your specific package manager](https://github.com/actions/cache/blob/main/examples.md). |
0 commit comments