如何在 GitHub Actions 中利用 cache 动作把校验耗时从 3min 降到 30s?

解读

面试官想验证三件事:

  1. 你是否清楚 Stylelint 在 CI 里“慢”的根因——每次流水线都重新安装依赖、重新构建缓存目录(.stylelintcache)。
  2. 你是否熟悉 GitHub Actions 的缓存机制(actions/cache 或 actions/setup-node 自带的 cache 字段)以及缓存键(key)的最佳实践。
  3. 你是否能把“缓存依赖 + 缓存 Stylelint 自身缓存文件”这两件事同时落地,并给出可量化的耗时对比。

国内场景下,网络镜像源(如淘宝源、npmmirror)与 GitHub 缓存服务(位于 Azure 东亚节点)的连通性也要考虑进去,否则“缓存命中”可能反而变慢。

知识点

  1. Stylelint 两种耗时来源
    • 依赖安装:node_modules 体积大,国内裸拉 npm 源耗时 2min+。
    • 文件遍历与解析:即使增量,无缓存时仍需 30s~1min。
  2. GitHub Actions 缓存三要素
    • key:决定唯一性,常用 OS + lockfile hash。
    • restore-keys:提供降级匹配策略。
    • path:支持多路径,用换行分隔。
  3. Stylelint 自带缓存
    • 默认文件 .stylelintcache,需显式传入 --cache --cache-location 才能生成。
    • 内容基于文件 mtime 与内容 hash,key 改变即失效。
  4. 国内镜像加速
    • 设置 npm config registry 或 ACTIONS_STEP_DEBUG =true 观察实际下载地址。
  5. 缓存失效策略
    • lockfile 变更 → 依赖缓存失效;
    • style 代码变更 → Stylelint 缓存可复用大部分,仅增量检查。

答案

步骤一:在 workflow 文件顶部定义缓存键模板

env:
  NODE_VERSION: '18'
  CACHE_KEY_PREFIX: stylelint-${{ runner.os }}-node${{ env.NODE_VERSION }}-

步骤二:同时缓存 node_modules 与 Stylelint 自身缓存

- name: 缓存依赖与 Stylelint 缓存
  uses: actions/cache@v4
  with:
    path: |
      ~/.npm
      node_modules
      .stylelintcache
    key: ${{ env.CACHE_KEY_PREFIX }}${{ hashFiles('package-lock.json') }}
    restore-keys: |
      ${{ env.CACHE_KEY_PREFIX }}

步骤三:安装依赖使用国内镜像并强制 prefer-offline

- name: 配置淘宝源
  run: npm config set registry https://registry.npmmirror.com
- name: 安装依赖
  run: npm ci --prefer-offline --no-audit --no-fund

步骤四:执行 Stylelint 带上缓存参数

- name: 运行 Stylelint
  run: npx stylelint "**/*.{css,scss}" --cache --cache-location .stylelintcache

步骤五:量化对比

  • 首次运行:依赖未命中,耗时≈3min。
  • 后续运行:依赖命中 + Stylelint 增量,耗时≈25–30s。

通过“双缓存”策略即可把平均校验耗时稳定压在 30s 以内。

拓展思考

  1. 大仓库下 .stylelintcache 体积膨胀怎么办?
    可在 job 末尾加一步“压缩缓存”:
    tar -zcf .stylelintcache.tar.gz .stylelintcache && mv .stylelintcache.tar.gz .stylelintcache
    并在下次解压,减少上传时间。
  2. 多项目复用缓存?
    把 key 前缀换成 ${{ github.repository_owner }} 级别,让组织内所有仓库共享一份 node_modules 缓存,降低整体排队时间。
  3. 缓存污染风险?
    在 PR 触发场景下,给 key 追加 ${{ github.event.pull_request.number }},防止 feature 分支的实验依赖污染主分支缓存。