前言
在先前的文章提到如何使用 Lighthouse 这款工具监控前端大大小小的最佳实践,例如:性能、SEO、适用性……等能被客观测量比较的数值:只要三步骤通过 Lighthouse CI 自动化检测网站性能,过程中上传对象设置为 Google 提供的免费暂存服务器:
upload: target: 'temporary-public-storage' # upload options here
虽然很方便但你可能会希望自建 Lighthouse 服务,以便实现:
- 收集与管理自己的隐私资料
- 持续性监控同个网站的检测资料
- 减少依赖第三方服务器服务
具体来说这篇文章会说明我根据官方文件:The Lighthouse CI Server 实现自建 Lighthouse。

Docker 自建 Lighthouse 服务器
官方文件提供了 本地自建 与 Docker 两种方式,基于这是个简单的小监测功能没有什么太复杂的流量或扩张需求,我是直接将 Docker 部署上 Zeabur 这样的平台,各平台的操作应该大同小异。
构建 Lighthouse 服务器
- 拿着官方提供的 Docker Image - patrickhulce/lhci-server 到平台上部署
- 根据官方设置设置
/data
为volumes
存放永久资料、设置默认9001 port
对外开放 - 使用
npx lhci wizard
指令初始化 Lighthouse 项目填写基本资料
$ npx lhci wizard # Use the wizard to create a project.? Which wizard do you want to run? new-project? What is the URL of your LHCI server? https://your-lhci-server.example.com/? What would you like to name the project? My Favorite Project? Where is the project's code hosted? https://github.com/GoogleChrome/lighthouse-ci
Created project My Favorite Project (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)!Use build token XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX to connect.Use admin token XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX to manage the project.
连接 Lighthouse 服务器
项目初始化后最终会拿到 build token
与 admin token
,根据官方安全性文件提到:
-
build token
:允许用户将新资料上传到特定项目,但不允许破坏或编辑任何历史资料。如果项目是开源的,并且想要收集来自外部贡献者的拉取请求的 Lighthouse 数据,那么应该公开。 -
admin token
:管理员令牌允许用户编辑或删除特定项目的资料。管理员令牌只能与受信任的用户共享,且绝不能放置在 CI 环境中,即使在有外部贡献者的开源项目中也是如此。任何拥有管理员令牌的人都可以删除整个项目的资料。
也就是说只要拿着 build token
就能上传最新的检测资料了,来到生成 lighthouse 报告的项目设置当中,重新设置 lighthouse upload 相关的属性:
module.exports = { ci: { collect: { numberOfRuns: 1, startServerCommand: 'pnpm astro preview', url: [ 'http://localhost:4321/en/', 'http://localhost:4321/en/resume/', 'http://localhost:4321/en/work/', 'http://localhost:4321/en/faq/', ], }, upload: { target: 'lhci', serverBaseUrl: 'https://lhci-weweweb.zeabur.app/', token: process.env.LHCI_TOKEN, }, },};
再调整一下 CI 要使用到的变量,并且到 GitHub Secrets 添加 build token
为 LHCI_TOKEN
。
- name: Run Lighthouse CI env: LHCI_TOKEN: ${{ secrets.LHCI_TOKEN }} run: pnpm dlx @lhci/cli@0.14.x autorun
接着就可以到 Lighthouse 服务器观察每一次 CI 提交的资料了。

总结
对我来说自建 Lighthouse 相较于使用 temporary-public-storage
或 PageSpeed Insights 有一个明显的好处是能够长期追踪项目的各方面最佳实践,而不只专注于单一次检测的结果,甚至能抓取不同的 Commit 时机查看每项评分的差距,对前端来说可说是酷炸了,长期检测下来也能让团队对代码质量有更高的认知与责任心。