GitHub Actions 中如何让多个 job 共享同一个缓存?

端木欧辰 阅读 2

我在 GitHub Actions 里写了两个 job,分别跑 build 和 test,但它们都依赖 node_modules。我试过在每个 job 里单独加 actions/cache,结果缓存没复用上,每次都要重新装依赖,特别慢。

看文档说 cache key 一致就能共享,但我这两个 job 的 key 都设成一样的了,还是不行。是不是 job 之间默认不能共享缓存?得怎么配置才行?

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/cache@v3
        with:
          path: ~/.npm
          key: npm-cache-${{ hashFiles('**/package-lock.json') }}
      # ... install and build

  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/cache@v3
        with:
          path: ~/.npm
          key: npm-cache-${{ hashFiles('**/package-lock.json') }}
      # ... install and test
我来解答 赞 0 收藏
二维码
手机扫码查看
1 条解答
Air-美美
问题很简单:你缓存的路径不对。

你缓存的是 ~/.npm,但实际需要缓存的是 node_modules 目录。npm 的全局缓存和项目依赖是两码事。

改一下 path 就好了:

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v3
with:
path: node_modules
key: npm-cache-${{ hashFiles('**/package-lock.json') }}
- run: npm install
- run: npm run build

test:
runs-on: ubuntu-latest
needs: build
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v3
with:
path: node_modules
key: npm-cache-${{ hashFiles('**/package-lock.json') }} - run: npm install
- run: npm test


不过更省心的做法是用 actions/setup-node,它自带缓存功能,只需要加一行 cache: 'npm' 就行:

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm install
- run: npm run build

test:
runs-on: ubuntu-latest
needs: build
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm install
- run: npm test


这样不用手动配 cache action,setup-node 会自动处理缓存的读写,key 也是基于 package-lock.json 生成的,完全不用你操心。
点赞
2026-03-20 10:07