GitHub Actions 缓存为什么没生效?

UX-成立 阅读 40

我在 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 啊?搞不懂到底哪里出问题了。

我来解答 赞 8 收藏
二维码
手机扫码查看
2 条解答
诸葛艳玲
你这个问题挺常见的,很多人都遇到过。看起来你的配置里有几个地方可能需要注意一下。

首先,缓存的路径应该是你项目里实际存放 node_modules 的地方,而不是 npm 的全局缓存目录 ~/.npm。所以你应该改成 ./node_modules。另外,restore-keys 也可以稍微调整一下,让它更有针对性。

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


这样改之后,workflow 应该能正确地缓存和恢复 node_modules 了。希望能帮到你!
点赞
2026-03-24 08:09
司空锦玉
兄弟,问题很简单,你的 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