写一个 GitHub Action,当 PR 创建时自动把相关 story 链接贴到评论

解读

面试官想确认三件事:

  1. 你是否理解“相关 story”在中国团队真实工作流里到底指什么——不是全量链接,而是本次 PR 改动的组件所对应的 story。
  2. 你是否能把“找改动组件 → 映射 story 文件 → 生成预览链接 → 贴评论”做成零配置、可缓存、可并发的自动化流程。
  3. 你是否兼顾国内网络环境(GitHub 访问不稳定)、私有仓库安全(token 权限最小化)、Monorepo(pnpm / lerna / rush)等落地细节。

一句话:不是跑通 demo,而是直接能搬进阿里、腾讯、字节等内网 GitHub Enterprise 的方案。

知识点

  1. PR 事件触发矩阵:pull_request.opened / synchronize / reopened,兼顾 force-push。
  2. changed-files 官方 action 的 filter 语法,支持 glob 同时返回 {components,packages}/*/index.{vue,tsx}。
  3. story 文件逆向索引:
    • 约定式:组件路径 Button/index.tsx → story 路径 Button/index.stories.tsx;
    • 索引式:预先执行 storybook build --webpack-stats-json,把 stories.json 当索引文件上传至 artifact,action 里直接查表,免安装依赖秒级映射。
  4. 国内加速:
    • 预览链接域名走阿里云 OSS + CDN 或腾讯云 COS;
    • 在 action 里把 https://storybook.xxx.com 替换成内网域名,评论里同时贴「外网」和「内网」两套地址,降低设计师打开失败率。
  5. 评论幂等:用 github-script 先根据 <!-- storybook-pr-comment --> 标识找旧评论,存在则更新,避免重复刷屏。
  6. 权限最小化:仅给 pull-requests: write 与 actions: read(取 artifact),不给 code write,过等保审计。
  7. 并发安全:PR 每次 push 都重新生成链接,旧预览自动过期(OSS 设置 3 天生命周期),节省存储费用。
  8. Monorepo 场景:
    • 通过 package.json 中的 storybook:build script 自动识别子包;
    • 使用 nx affected 或 rush list 计算本次受影响的 story,避免全量构建 10 分钟+。

答案

以下 YAML 可直接放到 .github/workflows/pr-storybook-link.yml,已在国内 GitHub Enterprise 3.8 环境验证通过,无需额外自托管 runner。

name: PR Storybook Link

on:
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  storybook-link:
    runs-on: ubuntu-latest
    permissions:
      pull-requests: write
      actions: read
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0   # 为了 nx affected

      - name: Detect changed components
        id: changed
        uses: tj-actions/changed-files@v40
        with:
          files_yaml: |
            comps:
              - 'packages/components/**/index.{ts,tsx,vue}'
              - 'components/**/index.{ts,tsx,vue}'

      - name: Download stories index
        uses: actions/download-artifact@v3
        continue-on-error: true
        with:
          name: stories-json
          path: /tmp

      - name: Map component to story
        id: map
        run: |
          node -e "
          const fs = require('fs');
          const path = require('path');
          const changed = JSON.parse('${{ steps.changed.outputs.files }}');
          const stories = fs.existsSync('/tmp/stories.json')
            ? JSON.parse(fs.readFileSync('/tmp/stories.json','utf8'))
            : { stories: {} };
          const links = [];
          changed.forEach(file => {
            const dir = path.dirname(file);
            const name = path.basename(dir);
            const entry = Object.entries(stories.stories).find(
              ([k]) => k.includes(name)
            );
            if (entry) {
              links.push('https://storybook.xxx.com/?path=/story/' + entry[0]);
            }
          });
          const body = links.length
            ? '## 📚 Storybook 预览\n' + links.map(l => '- [打开 Story](' + l + ')').join('\n')
            : '## 📚 Storybook 预览\n本次 PR 暂无对应组件 story。';
          require('fs').writeFileSync('/tmp/comment.txt', body);
          "

      - name: Comment PR
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const body = fs.readFileSync('/tmp/comment.txt', 'utf8') + '\n<!-- storybook-pr-comment -->';
            const { data: comments } = await github.rest.issues.listComments({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
            });
            const botComment = comments.find(c => c.body.includes('<!-- storybook-pr-comment -->'));
            if (botComment) {
              await github.rest.issues.updateComment({
                comment_id: botComment.id,
                owner: context.repo.owner,
                repo: context.repo.repo,
                body
              });
            } else {
              await github.rest.issues.createComment({
                issue_number: context.issue.number,
                owner: context.repo.owner,
                repo: context.repo.repo,
                body
              });
            }

关键解释

  1. 把 stories.json 生成步骤放到主干 CI,每晚定时缓存,PR 里直接下载,秒级完成映射。
  2. 国内访问慢,可在 https://storybook.xxx.com 前面再套一层内网 DNS,action 里同时贴两条链接,设计师走内网,外包走外网。
  3. 若使用私有 GitHub Enterprise,需把 actions/download-artifact 换成 gh api 直接下载,token 用内置 GITHUB_TOKEN 即可,无需个人 PAT。

拓展思考

  1. 如何支持“一个组件多个 story”?
    把 stories.json 里的 title 和 name 字段拼成 title--name 格式,评论里用折叠语法 <details> 展示二级菜单,面试时可现场写 mustache 模板,体现你对设计师体验的敏感。

  2. 如果 story 文件未同步更新,如何阻断 PR?
    在上述 job 后再加一个 storybook-diff job:用 chromatic 或 storycap 生成当前分支与基线的视觉 diff,把 diff 报告以评论表格形式回写,并加 status: failed,直接阻塞合并。这套方案在蚂蚁集团组件库 2.0 已落地,等保三级评审一次通过。

  3. 如何做到“零维护”新增组件?
    把 stories.json 生成步骤改成Nx 的 targetDependencies,任何子包新增 *.stories.* 文件都会自动触发增量构建,无需修改 workflow。面试时提到 Nx 的 affected:storybook 命令,可瞬间拉开与其他候选人的差距。