利用 addon-storysource 与 Lighthouse CI 检测首帧渲染时间

解读

面试官抛出此题,核心想验证三件事:

  1. 你是否真正理解 Storybook 的“源码即文档”理念,能把 addon-storysource 用成性能分析的“探针”;
  2. 你是否能把 Lighthouse CI 无缝嵌入国内主流 CI 环境(GitLab-CI、Jenkins、GitHub Actions 镜像加速),并解决“墙内拉取 Chrome 失败、Lighthouse 评分波动大”等现实痛点;
  3. 你是否能把“首帧渲染时间(First Contentful Paint)”这一指标与组件级 stories 一一映射,让性能回归成为每次 MR 的门禁红线,而不是事后报表。

一句话:不是问“怎么跑 Lighthouse”,而是问“怎么让 Lighthouse 在 Storybook 的每个 story 上稳定、可重复地跑出首帧指标,并阻断合并”。

知识点

  1. addon-storysource 的运行时注入机制:通过 babel-plugin-storysource 把 stories 的原始代码以 <storysource> 标签挂载到 window.STORYBOOK_STORY_SOURCE,供后续脚本精确拿到“当前 story 的入口文件路径”,从而告诉 Lighthouse 到底测哪一段。
  2. Storybook 的静态构建产物结构:storybook-static/index.html 是总壳,iframe.html 才是真实渲染区;Lighthouse 必须直接扫 iframe.html 并带上 ?path=/story/xxx--yyy 参数,否则会把导航壳算进 FCP,导致虚低 200-300 ms。
  3. Lighthouse CI 的断言模型:
    • .lighthouserc.js 里通过 url 数组把每个 story 的完整路径列出来;
    • assert.assertions.first-contentful-paint 设置 maxNumericValue: 1500;
    • 使用 median 运行三次取中位数,抵消国内云主机 CPU 抢占带来的毛刺 20-30 %。
  4. 国内镜像加速:
    • 用 cnpm 或 npmmirror 预装 @lhci/cli@0.12.x;
    • 在 Dockerfile 里把 PUPPETEER_DOWNLOAD_HOST=https://npmmirror.com/mirrors 写死,避免 Chrome 拉取超时;
    • CI 阶段缓存 ~/.cache/lighthouse/ 与 ~/.cache/puppeteer/,每次构建节省 3-4 min。
  5. Story 级别的性能基线:把每个 story 的“首次加载 bundle 体积”与“首帧时间”写回 JSON,上传到内部 OSS,再在 MR 阶段用 lhci assert --compareUrl=oss基线地址 做差值回归,防止“只改一行样式,FCP 飙高 400 ms”的隐蔽性能劣化。

答案

整体分四步落地,可直接写进简历的“性能门禁工程化实践”条目。

第一步:改造 Storybook
npm i -D addon-storysource babel-plugin-storysource
在 .storybook/main.js 注册:

addons: ['@storybook/addon-storysource']

babel.config.js 里追加:

plugins: ['babel-plugin-storysource']

构建后验证:访问任一 story,控制台执行 window.__STORYBOOK_STORY_SOURCE__[id] 能拿到源码路径,即表示注入成功。

第二步:生成待测 URL 列表
写脚本 scripts/gen-lhci-urls.js:

const stories = require('../storybook-static/stories.json');
const base = 'http://localhost:6006/iframe.html';
const urls = Object.keys(stories.stories).map(id =>
  `${base}?id=${id}&viewMode=story&globals=backgrounds.grid:!false`
);
require('fs').writeFileSync('.lhci-urls.json', JSON.stringify(urls, null, 2));

关键点:加 backgrounds.grid:!false 关闭网格层,避免额外 20 ms 绘制;用 iframe.html 而非 index.html,杜绝壳层干扰。

第三步:接入 Lighthouse CI
.lighthouserc.js:

module.exports = {
  ci: {
    collect: {
      startServerCommand: 'npx http-server storybook-static -p 6006 -c-1',
      url: require('./.lhci-urls.json'),
      numberOfRuns: 3,
      settings: {
        preset: 'desktop',
        throttling: {
          cpuSlowdownMultiplier: 1, // 国内云主机本身已慢,再降会失真
          rttMs: 40,
          throughputKbps: 10240
        }
      }
    },
    assert: {
      assertions: {
        'first-contentful-paint': ['error', { maxNumericValue: 1500, aggregationMethod: 'median' }]
      }
    },
    upload: {
      target: 'temporary-public-storage' // 也可改投阿里 OSS
    }
  }
};

GitLab-CI 片段:

lhci:
  image: registry.npmmirror.com/puppeteer/lighthouse-ci:v0.12.0
  variables:
    PUPPETEER_DOWNLOAD_HOST: "https://npmmirror.com/mirrors"
  script:
    - npm ci --registry=https://registry.npmmirror.com
    - npm run build-storybook
    - node scripts/gen-lhci-urls.js
    - lhci autorun
  artifacts:
    reports:
      performance: lhci-report.json
    expire_in: 7 days
  only:
    - merge_requests

门禁效果:FCP > 1500 ms 的 story 直接阻断 MR,无需人工盯报表。

第四步:把首帧时间写回 Storybook 面板
自定义 addon lighthouse-panel:

import { useParameter } from '@storybook/api';
export const Panel = () => {
  const { fcp } = useParameter('lighthouse', {});
  return <div>首帧 {fcp} ms</div>;
};

在 preview.js 里把 CI 产物 lhci-report.json 读进来,按 storyId 塞到 parameters.lighthouse,让开发者在本地就能看见上次 CI 跑出来的真实 FCP,实现“文档即性能看板”。

拓展思考

  1. 组件级懒加载对首帧的影响:若 story 里用了 React.lazy,Lighthouse 会把首次渲染拆成两段,FCP 会提前 100-200 ms,但 LCP 可能反而延后;此时需在断言里同时加 LCP 阈值,防止“虚假胜利”。
  2. 微前端场景下,子应用 story 被嵌在 Shell 里跑 CI,需把 window.__POWERED_BY_QIANKUN__ 写进 user-agent,Lighthouse 才会按微前端模板做资源去重,否则会把主框架重复算入,FCP 虚高 30 %。
  3. 设计 Token 改动引发性能回退:比如把 --primary-color 从 #1890ff 改成渐变,浏览器需额外生成纹理;可把颜色值哈希作为环境变量写进 CI,当 Token 变动时自动触发全量性能回归,而不是仅跑差异 story。
  4. 国内移动端适配:若项目需跑微信小程序组件库,Storybook 通过 storybook-miniprogram 渲染,Lighthouse 无法直接测;可改用Puppeteer 桥接真机 Chrome DevTools Protocol,把 performance.getMetrics() 里的 FIRST_CONTENTFUL_PAINT 回写 LHCI,曲线实现“首帧门禁”。