如何编写 GitHub Actions 缓存 node_modules?

解读

在国内前端面试中,CI/CD 已成为“必答题”。面试官问“如何缓存 node_modules”,表面看是考察 GitHub Actions 语法,实则想确认三点:

  1. 你是否理解 npm 依赖树体积巨大 带来的网络与磁盘 IO 瓶颈;
  2. 你是否掌握 缓存键(key)与恢复键(restore-keys) 的失效策略,避免“幽灵缓存”;
  3. 你是否能把 Gulp 这类 流式构建工具 的启动时间压到最低,让流水线真正提速。
    答得太浅(只写 actions/cache@v3 with: path: node_modules)会被追问“缓存键怎么设计”;答得太深(自建镜像、pnpm 全局 store)又容易脱离团队现状。最佳策略是给出“可落地的三段式 YAML”,并解释每一行的防御性考虑。

知识点

  1. 缓存键设计范式:
    一级精确:package-lock.json 的哈希 → 保证依赖完全一致;
    二级降级:os+node 版本 → 当 lock 文件变更后仍可复用部分缓存,减少完全重装的概率。
  2. 缓存路径:
    不仅要缓存 node_modules,还要把 ~/.npm/_cacache 一起缓存,否则 npm ci 仍会重新下载 tarball。
  3. Gulp 与缓存的耦合:
    Gulp 本身无缓存状态,但插件如 gulp-sass 会调用 node-sass 原生模块;原生模块路径在 node_modules 内,因此 node_modules 必须整目录缓存,否则 postinstall 脚本会重新编译,抵消缓存收益。
  4. 国内网络补偿:
    即使命中缓存,首次安装仍可能因“npm 官方源 443 超时”失败;要在 YAML 里前置 registry=https://registry.npmmirror.com 并锁定 chromedriver、sass_binary_site 等镜像,避免缓存命中后仍然失败。
  5. 缓存上限与清理:
    GitHub 免费仓库 10 GB 缓存配额,超出后按 LRU 淘汰;建议每月在 README 加 手动触发 workflow_dispatch 的清理任务,防止“僵尸缓存”堆积。

答案

以下 YAML 可直接放入 .github/workflows/ci.yml,兼顾缓存命中率、安全性与国内镜像,并针对 Gulp 项目做了专项优化:

name: CI

on:
  push:
    branches: [main, develop]
  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 18
          # 关键:让 npm 走国内镜像
          registry-url: 'https://registry.npmmirror.com'

      - name: Get npm cache dir
        id: npm-cache-dir
        run: echo "dir=$(npm config get cache)" >> $GITHUB_OUTPUT

      - name: Cache node_modules & npm cache
        uses: actions/cache@v4
        id: cache-node-modules
        with:
          path: |
            node_modules
            ${{ steps.npm-cache-dir.outputs.dir }}
          # 一级精确:lock 文件哈希;二级降级:系统+版本
          key: ${{ runner.os }}-node18-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node18-

      - name: Install dependencies
        if: steps.cache-node-modules.outputs.cache-hit != 'true'
        run: npm ci --prefer-offline --no-audit --progress=false

      - name: Build with Gulp
        run: npx gulp build --colors

要点拆解:

  1. path 字段同时写入 node_modules 与 npm 缓存目录,保证 npm ci 完全离线。
  2. key 采用二级降级策略,lock 文件变化后仍可利用系统级缓存,节省 30~60 秒。
  3. cache-hit 判断避免重复执行 npm ci,防止 Gulp 任务因二次安装触发 node-gyp 重编译。
  4. npx gulp build 而非全局 gulp,确保版本与 lock 文件一致,排除“全局老版本 gulp”副作用。
  5. 全程使用 registry.npmmirror.com,即便缓存未命中,也能在 20 秒内完成依赖下载,符合国内网络现实。

拓展思考

  1. pnpm 场景:若团队已迁移 pnpm,则缓存路径应改为
    ~/.local/share/pnpm/store/v3
    并把 key 后缀改为 pnpm-lock.yaml,可将缓存体积从 400 MB 压缩到 80 MB,命中率更高。
  2. 多工作流复用:把“缓存+安装”封装成 可调用 workflow(workflow_call),让 lint、test、build 三个 job 共享同一份 node_modules,避免重复下载。
  3. Gulp 4 的增量构建:结合 gulp.lastRun() 与 GitHub Actions 的 artifact 缓存,可以把编译结果(dist 目录)也缓存起来,实现“秒级增量上线”。
  4. 缓存失效演练:在 MR 阶段故意修改一处 Sass 变量,观察流水线是否精准失效并重编译,验证缓存键设计是否严谨。
  5. 安全红线:不要把 .npmrc 中的私有 token 写进缓存路径;使用 actions/setup-node 自带的 registry-url 与 scope 参数,可在缓存层之外解决认证问题,避免 token 被缓存泄露。