GitHub Actions CI流水线每次运行都会重新安装依赖,缓存策略没生效怎么办?

码农文鑫 阅读 29

最近在给项目配置GitHub Actions的CI流水线,按照教程设置了npm缓存,但每次提交代码后还是能看到`npm install`重新执行,缓存似乎没起作用。我的工作流配置里明明写了`npm ci –cache .npm`和`cache`步骤,但日志显示缓存命中率一直是0%。之前试过改缓存密钥为`npm-deps-${{ github.sha }}`,也尝试过用`npm ci`替代`npm install

,但都没用...</p>  

<p>项目用的是Yarn 3,可能是缓存策略需要调整?附上当前的workflow片段和package.json里的相关配置:</p>  

<pre class="pure-highlightjs line-numbers"><code class="language-css">
/* 这个样式文件每次修改都会触发CI,但和缓存问题无关 */
body {
  background: linear-gradient(45deg, #ff00ff, #00ffff);
}
</code></pre>  

<p>流水线报错时显示

Cache not restored

,但我的步骤是这样写的:<code>runs-on: ubuntu-latest</code>后面跟着:</p>  

<pre class="pure-highlightjs line-numbers"><code class="language-javascript">
- name: Cache node-modules
  uses: actions/cache@v3
  with:
    path: node_modules
    key: ${{ runner.os }}-npm-deps-${{ hashFiles('**/package-lock.json') }}
</code></pre>  

<p>是不是因为用了Yarn导致缓存路径不对?或者需要单独缓存

.yarn/cache`目录?

我来解答 赞 8 收藏
二维码
手机扫码查看
2 条解答
Air-一可
你用的是Yarn 3,但缓存配置还是按照npm的方式写的,这肯定不行啊。Yarn 3的缓存目录是.yarn/cache,而不是node_modules。你需要调整缓存路径和key。

代码放这了:


- name: Cache Yarn dependencies
uses: actions/cache@v3
with:
path: .yarn/cache
key: ${{ runner.os }}-yarn-deps-${{ hashFiles('**/yarn.lock') }}


另外,确保你的项目里有yarn.lock文件,没有的话生成一个。如果还用package-lock.json就别怪缓存不命中了,Yarn和npm的锁文件不能混着用。

最后提醒一下,Yarn 3可能会用到零安装(Plug'n'Play, PnP)模式,这种情况下连node_modules都没有,直接依赖.yarn/cache里的内容。所以一定要检查项目的Yarn配置,别搞错了。
点赞 10
2026-02-02 18:05
爱学习的炳钛
你用的是 Yarn 3,缓存路径确实变了,node_modules 和传统的 npm 缓存方式不一样。直接这样:


- name: Cache Yarn
uses: actions/cache@v3
with:
path: .yarn/cache
key: ${{ runner.os }}-yarn3-${{ hashFiles('**/yarn.lock') }}


同时别忘了确保你的项目里有 yarn.lock 文件,没有的话生成一个。老项目切换 Yarn 3 确实要调整缓存策略,官方文档有时候也不靠谱,直接按这个来就行。
点赞 7
2026-01-31 10:00