GitHub Actions 缓存为什么没生效?

UX-成立 阅读 9

我在 GitHub Actions 里用了 actions/cache 来缓存 node_modules,但每次跑 workflow 都重新安装依赖,感觉缓存根本没用上。我 key 是用 node-modules-${{ hashFiles('package-lock.json') }},restore-keys 也配了,但还是不行。

这是我的配置片段:

- name: Cache node modules
  uses: actions/cache@v3
  with:
    path: ~/.npm
    key: node-modules-${{ hashFiles('package-lock.json') }}
    restore-keys: |
      node-modules-

是不是路径写错了?我看有些项目用的是 ./node_modules,但文档说 npm 缓存应该在 ~/.npm 啊?搞不懂到底哪里出问题了。

我来解答 赞 2 收藏
二维码
手机扫码查看
1 条解答
司空锦玉
兄弟,问题很简单,你的 path 写错了。

你缓存的是 ~/.npm,但这个是 npm 下载包时的缓存目录,不是 node_modulesnpm install 每次还是会重新构建 node_modules 目录,所以你觉得缓存没用上。

正确的配置应该是缓存项目里的 node_modules 目录:

- name: Cache node modules
uses: actions/cache@v3
with:
path: node_modules
key: node-modules-${{ hashFiles('package-lock.json') }}
restore-keys: |
node-modules-


另外 restore-keys 这里也有点问题。你写的是 node-modules-,这在 key 不匹配时确实会尝试找前缀匹配的缓存,但最好写成这样更稳妥:

restore-keys: |
node-modules-${{ hashFiles('package-lock.json') }}-


这样当 package-lock.json 变化时,会优先找上一次相同 hash 前缀的缓存,能命中部分缓存。

总结一下:就一个问题,把 path 改成 node_modules 就完事了。
点赞 1
2026-03-10 20:16