perf-lighthouse について
Webサイトの品質確認やビルド間の変化追跡に使う、Lighthouse監査の実行・自動化ガイドです。監査オプション、パフォーマンス予算、CI連携、レポート比較を扱います。
主な機能
- 01Lighthouse監査の実行
- 02デバイスと監査カテゴリの選択
- 03リソースのパフォーマンス予算設定
- 04Lighthouse CIによる連携
- 05JSONレポートの解析と比較
活用シーン
- 01サイトのパフォーマンスとアクセシビリティの確認
- 02CIワークフローでの監査実行
- 03ビルド間の指標変化の比較
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ tech-leads-club/ agent-skills --skill perf-lighthouseインストール後、Claude Code で/perf-lighthouseを入力して読み込まれたか確認します。
詳細
Lighthouse 監査
CLI クイックスタート
# Install
npm install -g lighthouse
# Basic audit
lighthouse https://example.com
# Mobile performance only (faster)
lighthouse https://example.com --preset=perf --form-factor=mobile
# Output JSON for parsing
lighthouse https://example.com --output=json --output-path=./report.json
# Output HTML report
lighthouse https://example.com --output=html --output-path=./report.html
よく使うフラグ
--preset=perf # Performance only (skip accessibility, SEO, etc.)
--form-factor=mobile # Mobile device emulation (default)
--form-factor=desktop # Desktop
--throttling-method=devtools # More accurate throttling
--only-categories=performance,accessibility # Specific categories
--chrome-flags="--headless" # Headless Chrome
パフォーマンス予算
budget.json を作成します。
[
{
"resourceSizes": [
{ "resourceType": "script", "budget": 200 },
{ "resourceType": "image", "budget": 300 },
{ "resourceType": "stylesheet", "budget": 50 },
{ "resourceType": "total", "budget": 500 }
],
"resourceCounts": [{ "resourceType": "third-party", "budget": 5 }],
"timings": [
{ "metric": "interactive", "budget": 3000 },
{ "metric": "first-contentful-paint", "budget": 1500 },
{ "metric": "largest-contentful-paint", "budget": 2500 }
]
}
]
予算を指定して実行します。
lighthouse https://example.com --budget-path=./budget.json
Node API
import lighthouse from 'lighthouse'
import * as chromeLauncher from 'chrome-launcher'
async function runAudit(url) {
const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless'] })
const result = await lighthouse(url, {
port: chrome.port,
onlyCategories: ['performance'],
formFactor: 'mobile',
throttling: {
cpuSlowdownMultiplier: 4,
},
})
await chrome.kill()
const { performance } = result.lhr.categories
const { 'largest-contentful-paint': lcp } = result.lhr.audits
return {
score: Math.round(performance.score * 100),
lcp: lcp.numericValue,
}
}
GitHub Actions
# .github/workflows/lighthouse.yml
name: Lighthouse
on:
pull_request:
push:
branches: [main]
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build site
run: npm ci && npm run build
- name: Run Lighthouse
uses: treosh/lighthouse-ci-action@v11
with:
urls: |
http://localhost:3000
http://localhost:3000/about
budgetPath: ./budget.json
uploadArtifacts: true
temporaryPublicStorage: true
env:
LHCI_GITHUB_APP_TOKEN: ${{ secrets.LHCI_GITHUB_APP_TOKEN }}
Lighthouse CI(LHCI)
履歴を追跡しながら CI と完全に統合するには、次のようにします。
# Install
npm install -g @lhci/cli
# Initialize config
lhci wizard
lighthouserc.js が作成されます。
module.exports = {
ci: {
collect: {
url: ['http://localhost:3000/', 'http://localhost:3000/about'],
startServerCommand: 'npm run start',
numberOfRuns: 3,
},
assert: {
assertions: {
'categories:performance': ['error', { minScore: 0.9 }],
'categories:accessibility': ['warn', { minScore: 0.9 }],
'first-contentful-paint': ['error', { maxNumericValue: 1500 }],
'largest-contentful-paint': ['error', { maxNumericValue: 2500 }],
'cumulative-layout-shift': ['error', { maxNumericValue: 0.1 }],
},
},
upload: {
target: 'temporary-public-storage', // or 'lhci' for self-hosted
},
},
}
実行します。
lhci autorun
JSON レポートを解析する
import fs from 'fs'
const report = JSON.parse(fs.readFileSync('./report.json'))
// Overall scores (0-1, multiply by 100 for percentage)
const scores = {
performance: report.categories.performance.score,
accessibility: report.categories.accessibility.score,
seo: report.categories.seo.score,
}
// Core Web Vitals
const vitals = {
lcp: report.audits['largest-contentful-paint'].numericValue,
cls: report.audits['cumulative-layout-shift'].numericValue,
fcp: report.audits['first-contentful-paint'].numericValue,
tbt: report.audits['total-blocking-time'].numericValue,
}
// Failed audits
const failed = Object.values(report.audits)
.filter((a) => a.score !== null && a.score < 0.9)
.map((a) => ({ id: a.id, score: a.score, title: a.title }))
ビルドを比較する
# Save baseline
lighthouse https://prod.example.com --output=json --output-path=baseline.json
# Run on PR
lighthouse https://preview.example.com --output=json --output-path=pr.json
# Compare (custom script)
node compare-reports.js baseline.json pr.json
シンプルな比較スクリプト:
const baseline = JSON.parse(fs.readFileSync(process.argv[2]))
const pr = JSON.parse(fs.readFileSync(process.argv[3]))
const metrics = ['largest-contentful-paint', 'cumulative-layout-shift', 'total-blocking-time']
metrics.forEach((metric) => {
const base = baseline.audits[metric].numericValue
const current = pr.audits[metric].numericValue
const diff = (((current - base) / base) * 100).toFixed(1)
const emoji = current <= base ? '✅' : '❌'
console.log(`${emoji} ${metric}: ${diff}% (${base.toFixed(0)} → ${current.toFixed(0)})`)
})
トラブルシューティング
| 問題 | 解決方法 |
|---|---|
| スコアにばらつきがある | 複数回実行し(--number-of-runs=3)、中央値を使用します |
| Chrome が見つからない | CHROME_PATH 環境変数を設定します |
| タイムアウトする | --max-wait-for-load=60000 で待機時間を延長します |
| 認証が必要 | --extra-headers または puppeteer スクリプトを使用します |
コメント
Markdown 対応