如何集成 Lighthouse-CI?
解读
在国内前端面试中,“如何集成 Lighthouse-CI” 并不是单纯问命令行怎么跑,而是考察候选人能否把性能监控与Sass 工程化体系无缝结合。面试官想听到的是:
- 你能在已有 Sass → CSS 构建链路里插入 Lighthouse-CI,而不破坏现有流水线;
- 你知道国内网络环境(Chrome 下载、GitHub 连通性、私有仓库权限)带来的坑,并给出可落地的私有化或镜像方案;
- 你能把 Lighthouse 得分作为MR 门禁,并针对 Sass 产物(如超大 CSS 文件、未使用的 Mixin)给出可量化的优化指标。
回答时务必把“Sass 编译 → 静态部署 → Lighthouse-CI 采样 → 报告回写”整条链路讲完整,并突出CI 阶段与 Sass 变量的联动优化这一亮点。
知识点
- Lighthouse-CI 核心命令:lhci autorun、lhci upload、lhci assert
- Sass 编译后产物指纹化:contenthash 与 source-map 对性能指标的影响
- 国内镜像:npmmirror 的 chromium 镜像、Tencent Cloud 的 Lighthouse-CI server 镜像
- 私有 Git 仓库触发:Gitee 企业版 WebHook、GitLab CI 的 merge_request_event
- 断言规则:resource-summary.maxTransferSize 针对 CSS 体积、unused-css-rules 针对 Sass 未引用 Mixin
- 性能预算文件:budget.json 与 lighthouserc.js 的联动写法
- 并行流水线:把 Sass 编译任务与 Lighthouse 采样任务拆成独立 Job,减少排队
- 报告回写:将得分写入 MR 评论与内部钉钉群机器人,实现国内 IM 可达性
答案
-
安装与镜像加速
在项目根目录执行
npm i -D @lhci/cli puppeteer
并在 .npmrc 里加
puppeteer_download_host=https://npmmirror.com/mirrors
保证国内网络一次拉通。 -
编译链路插桩
在 Sass 出口加指纹:
sass src/index.scss dist/index.[contenthash:8].css --style=compressed
同时生成 source-map,供 Lighthouse 定位未使用规则。 -
配置 lighthouserc.js
module.exports = {
ci: {
collect: {
startServerCommand: 'npm run serve:dist',
url: ['http://localhost:4000/'],
numberOfRuns: 3,
settings: {
preset: 'desktop',
extraHeaders: { 'Accept-Language': 'zh-CN' }
}
},
assert: {
assertions: {
'resource-summary:stylesheet:maxTransferSize': ['error', { maxNumericValue: 80 * 1024 }],
'unused-css-rules': ['warn', { maxLength: 0 }]
}
},
upload: {
target: 'temporary-public-storage'
}
}
};
其中 maxTransferSize 80 kB 直接约束 Sass 编译后体积,unused-css-rules 可反向驱动删除无用 Mixin。 -
接入 CI
以 GitLab CI 为例:
stages: [sass, deploy, lighthouse]
sass-build:
stage: sass
script: npm run build:css
artifacts:
paths: [dist/]
deploy-preview:
stage: deploy
script: npx surge ./dist https://CI_COMMIT_REF_SLUG-surge.surge.sh
lighthouse:
stage: lighthouse
image: cimg/node:18.16
script:
- npm i -g @lhci/cli
- lhci autorun
allow_failure: false
把 deploy-preview 产物地址动态注入 lighthouserc.js,实现分支级性能门禁。 -
私有化报告(可选)
若公司代码在 Gitee 私有仓,可自建 Lighthouse-CI server:
docker run -d -p 9001:9001 patrickhulce/lhci-server
并在 upload.target 改设为 'lhci',endpoint 指向内网域名,确保数据不出境。 -
结果回写
通过 lhci upload 的 webhook 把 summary 发到钉钉群,格式:
“分支 feature/card-ui Lighthouse 得分 96,CSS 体积 73 kB,未使用规则 0,准许合并”。
让产品、测试一眼看懂 Sass 优化效果。
拓展思考
- 如果 Sass 采用主题变量动态换肤,需在 Lighthouse 采样前多跑几种主题色,并在 lighthouserc.js 里用 matrix 策略并行采样,避免深色主题因高对比色导致 LCP 抖动。
- 对于微前端子应用,Sass 产物仅为局部样式,可把 Lighthouse-CI 的 onlyCategories: ['performance'] 与 block-all-mixed-content 结合,屏蔽主应用干扰,精准测量子应用 CSS 加载瓶颈。
- 在预算收紧的国企项目里,可把 Lighthouse 得分直接写进 Sass 的 README 徽章,并绑定晋升 KPI:“若 MR 导致性能分低于 90,需提交 Sass 重构方案”,让性能预算与代码质量强挂钩。