Chcek website performance with lighthouse CI

透過 Lighthouse CI 自動化檢測網站效能

前言

近期替這個部落格添加了 Lighthouse CI 用於檢測網頁效能,原先平時都是依靠 PageSpeed Insights🔗 這類手動工具來檢測,但是這樣的方式有以下幾個缺點:

  • 單次的測驗結果不穩定
  • 手動測試耗時費力
  • 不利於團隊開發

希望將效能檢驗這件事達成自動化驗證,就不用每次過了很久才知道某個頁面的效能或無障礙有問題,可以在問題發生的當下及時修復。

Lighthouse CI

第一步:建立設定檔

可以在專案根部建立一個 lighthouse CI 設定檔🔗 支援各式各樣檔案格式,像是我的部落格就是使用 .lighthouserc.yml 來設定:

ci:
collect:
numberOfRuns: 3
assert:
preset: 'lighthouse:no-pwa'
assertions:
csp-xss: 'warn'
total-byte-weight: 'off' # TODO: enable this when this bug is fixed: https://github.com/GoogleChrome/lighthouse-ci/issues/1001
identical-links-same-purpose: 'off'
upload:
target: 'temporary-public-storage'
# upload options here
server:
# server options here
wizard:
# wizard options here

這些設定檔參數都可以參考 Lighthouse CI 配置文件🔗 來設定應該如何檢測網頁效能,像是要測驗幾次、測驗資料夾的深度、測驗結果的存放位置……等。目前我的設定是關閉一些不需要的檢測項目、PWA 驗證,並且設定每個頁面測驗次數為 3 次,預設會偵測🔗到我專案中的 dist 資料夾內的所有頁面。

第二步:生成檢測報告

建立好設定檔之後可以透過執行 Lighthouse CI 來產生檢測報告,我的作法是下載相關套件 @lhci/cli 並在 package.json 中加入指令於本地端執行:

"scripts": {
"lighthouse": "lhci autorun"
}

等到在本地修復好現有問題後就可以把整個流程搬運到 CI 上,這裡我使用 GitHub Action 來執行 Lighthouse CI🔗

- name: Build
run: pnpm build
- name: Lighthouse
run: pnpm lhci autorun

總結

這樣不到 3 步驟就輕鬆替我的網站添加了 Lighthouse CI 來檢測網頁效能,不用再手動測試每個頁面,只要每次提交代碼就能自動檢測效能問題,這樣的方式對於團隊開發來說是一個很好的效能檢測工具,也能讓開發者更快速的修復問題。 可以參考看看這則分支🔗來了解我在部落格中添加 Lighthouse CI 的過程。