如何用 GitHub Actions 自动评论性能预算?

解读

在国内前端团队普遍采用“性能预算(Performance Budget)”作为上线门禁的背景下,面试官真正想考察的是:

  1. 你是否理解“把性能指标固化到 CI 流程”而非本地手动跑 Lighthouse;
  2. 能否用 GitHub Actions 的事件驱动模型(pull_request、workflow_run)在 MR 阶段给出可量化、可阻断、可回溯的评论;
  3. 是否熟悉Sass 产物体积对性能预算的影响(CSS 文件大小、复用率、未用样式剔除),并能将 Sass 编译步骤与预算检测无缝串联。

一句话:让每一次样式变更都自动算钱(预算),超标就回帖警告,并阻断合并。

知识点

  1. 性能预算模型:国内大厂普遍采用“3G 下 FCP < 1.8 s、CSS 体积 < 60 KB(gzip)”双指标,需同时满足。
  2. GitHub Actions 触发器:pull_request(同步代码)、workflow_run(等待 Sass 编译完成)两种事件组合,避免竞态。
  3. Sass 编译缓存:使用 actions/cache 对 node_modules/.cache/sass 做哈希缓存,缩短 CI 时间 30%+。
  4. 预算采集工具:Lighthouse CI(@lhci/cli)+ 自定义 budget.json;对纯样式项目可简化为“sass-bundle-analyzer”统计最终 CSS 体积。
  5. 评论策略:通过 github-script 调用 REST API,以 bot 身份发布 markdown 表格(此处仅文字描述),并打上 performance-budget 标签,方便后续度量。
  6. 阻断合并:国内代码平台(Gitee、Coding)同样支持 status check,需返回 neutral 或 failure 状态,配合分支保护规则实现“超标不可合并”。

答案

  1. 在仓库根目录创建 .github/workflows/perf-budget.yml:

    • 触发条件:
      on:
        pull_request:
          paths: ['src/**/*.scss', 'budget.json']
      
    • 关键步骤:
      a. 检出代码 + setup-node(指定国内镜像 registry.npmmirror.com,避免 install 超时)。
      b. 缓存 Sass 依赖:
      - uses: actions/cache@v3
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
      
      c. 编译 Sass(dart-sass):
      npx sass src/index.scss dist/index.css --style=compressed --no-source-map
      
      d. 采集预算:
      npx lhci autorun --config=lighthouserc.json
      
      其中 budget.json 示例:
      [
        {
          "resourceType": "stylesheet",
          "budget": 60
        }
      ]
      
      e. 解析结果并写评论:
      - uses: actions/github-script@v6
        with:
          script: |
            const fs = require('fs');
            const lhr = JSON.parse(fs.readFileSync('.lighthouseci/lhr-0.json','utf8'));
            const cssBytes = lhr.audits['resource-summary'].details.items
                             .find(i=>i.resourceType==='stylesheet').transferSize;
            const body = `**性能预算报告**\nCSS 体积:${(cssBytes/1024).toFixed(1)} KB\n状态:${cssBytes>61440?'❌ 超标':'✅ 通过'}`;
            github.rest.issues.createComment({...context.repo, issue_number: context.payload.number, body});
      
    • 返回状态:
      - run: exit $((${{ steps.lhci.outputs.failures }} > 0 ? 1 : 0))
      
      使 PR 出现红叉,满足国内“红线不可合并”规范。
  2. 若项目仅关心样式体积,可省略 Lighthouse,改用:

    gzip-size dist/index.css | awk '{if($1>61440) exit 1}'
    

    直接返回 exit code,逻辑更轻量。

拓展思考

  1. Sass 模块系统与预算联动:利用 @use 'bootstrap' as * 时,通过 sass-true 单元测试统计每个模块编译后体积,实现“按模块预算”,避免“全量引入”导致一次性超标。
  2. 国内网络优化:GitHub Actions runner 在境外,可将 Lighthouse 采集步骤拆分到 self-hosted runner(阿里云 ECS 上海区),降低 3G 节流模拟偏差,结果更贴近国内用户。
  3. 渐进式预算:对老项目设置“只减不增”策略——若本次 PR 的 CSS 体积增量 > 0,则评论中提示“请同步删除未用样式”,并给出 PurgeCSS 扫描报告链接(仅文字描述),推动团队逐步偿还技术债。