GitHub Actions 缓存为什么没生效?
我在 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 啊?搞不懂到底哪里出问题了。
你缓存的是
~/.npm,但这个是 npm 下载包时的缓存目录,不是node_modules。npm install每次还是会重新构建 node_modules 目录,所以你觉得缓存没用上。正确的配置应该是缓存项目里的
node_modules目录:另外 restore-keys 这里也有点问题。你写的是
node-modules-,这在 key 不匹配时确实会尝试找前缀匹配的缓存,但最好写成这样更稳妥:这样当 package-lock.json 变化时,会优先找上一次相同 hash 前缀的缓存,能命中部分缓存。
总结一下:就一个问题,把 path 改成
node_modules就完事了。