はじめに: オプションではなく要件としてのパフォーマンス
Web パフォーマンスは、「時間があるときに」最適化できるものではありません。ミリ秒ごと 読み込みの遅延はユーザーの喪失につながります: Google によると、ユーザーの 53% モバイルでは、読み込みに 3 秒以上かかるとサイトから離脱します。ザ パフォーマンスの予算 パフォーマンスを曖昧な目標からパイプライン内で測定可能な自動化された制約に変換します。 CI/CD。
この記事では、完全なパフォーマンス監視システムをセットアップします。
の予算の定義から angular.json の統合に向けて
ライトハウスCI GitHub Actions パイプライン内で、
メトリクスが標準を満たしていない場合はデプロイします。
この記事で学べること
- パフォーマンスバジェットとは何か、またそれが重要である理由
- 予算を設定する方法
angular.json - Lighthouse CI (lhci) をインストールおよび設定する方法
- ファイルの構造
lighthouserc.js - アサーションと品質しきい値を定義する方法
- Lighthouse CI を GitHub Actions と統合する方法
- 経時的にスコアを追跡する方法
- バンドルのサイズを追跡する方法
- SpeedCurveとCalibreとの比較
- リグレッションが発生した場合にビルドを失敗させる方法
1. パフォーマンスバジェットとは何ですか
Un パフォーマンス予算 および 1 つ以上のメトリクスに対する事前定義された最大制限 パフォーマンスの。予算を超えるとビルドが失敗し、デプロイができなくなります。 ユーザーエクスペリエンスを低下させるコード。最も一般的な予算は次のとおりです。
パフォーマンスバジェットメトリクス
| メトリック | 説明 | 推奨予算 |
|---|---|---|
| バンドルサイズ | JavaScript ファイルと CSS ファイルの合計サイズ | 初期 JS < 300 KB (gzip) |
| LCP | 最大のコンテンツフル ペイント: 最大のアイテムをレンダリングする時間 | < 2.5 秒 |
| FID/INP | 次のペイントへのインタラクション: インターフェースの応答性 | < 200 ミリ秒 |
| CLS | 累積的なレイアウト シフト: 読み込み時の視覚的な安定性 | < 0.1 |
| FCP | 最初のコンテンツフルペイント: 最初に表示されるコンテンツ | < 1.8秒 |
| TTI | インタラクティブになるまでの時間: ページがインタラクティブになるとき | < 3.8秒 |
2. angular.json のパフォーマンス バジェット
Angular は、現時点でのバンドルのサイズを制御する組み込みの予算システムを提供します ビルドの。予算を超えると、ビルドによって警告またはエラーが生成されます。
{
"projects": {
"my-app": {
"architect": {
"build": {
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "400kb",
"maximumError": "500kb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "4kb",
"maximumError": "8kb"
},
{
"type": "anyScript",
"maximumWarning": "150kb",
"maximumError": "200kb"
},
{
"type": "any",
"maximumWarning": "300kb",
"maximumError": "500kb"
}
]
}
}
}
}
}
}
}
Angular バジェットのタイプ
| タイプ | 説明 |
|---|---|
initial |
初期バンドル サイズ (メイン + ポリフィル + スタイル) |
anyComponentStyle |
単一コンポーネント CSS のサイズ |
anyScript |
単一の JavaScript ファイルのサイズ |
any |
バンドル内の個々のファイルのサイズ |
allScript |
すべての JavaScript ファイルの合計サイズ |
all |
バンドル内のすべてのファイルの合計サイズ |
bundle |
特定のバンドルのサイズ (名前別) |
3. ライトハウス CI セットアップ
Lighthouse CI (LHCI) は、Lighthouse 監査を自動化するための Google の公式ツールです CI/CD パイプライン内。パフォーマンス、アクセシビリティ、ベストプラクティス、SEO のスコアを提供します。
# Installare Lighthouse CI
npm install -D @lhci/cli
# Oppure globalmente
npm install -g @lhci/cli
# Verificare l'installazione
lhci --version
# Eseguire un audit locale
lhci autorun
Lighthouserc.js の設定
ファイル lighthouserc.js プロジェクトルートで動作を設定します
ライトハウスCI。 Angular プロジェクトの完全なセットアップは次のとおりです。
// lighthouserc.js
module.exports = {
ci: {
collect: {
// Quante volte eseguire l'audit (per risultati stabili)
numberOfRuns: 3,
// URL da testare (dopo aver avviato il server)
url: ['http://localhost:4200/'],
// Avviare il server prima del test
startServerCommand: 'npx ng serve --configuration=production',
startServerReadyPattern: 'Angular Live Development Server',
startServerReadyTimeout: 30000,
// Impostazioni Chrome
settings: {
chromeFlags: '--no-sandbox --headless --disable-gpu',
// Simulare una connessione 4G
throttling: {
rttMs: 150,
throughputKbps: 1638.4,
cpuSlowdownMultiplier: 4,
},
},
},
assert: {
assertions: {
// Performance
'categories:performance': ['error', { minScore: 0.9 }],
'first-contentful-paint': ['warn', { maxNumericValue: 2000 }],
'largest-contentful-paint': ['error', { maxNumericValue: 2500 }],
'cumulative-layout-shift': ['error', { maxNumericValue: 0.1 }],
'total-blocking-time': ['warn', { maxNumericValue: 300 }],
'speed-index': ['warn', { maxNumericValue: 3000 }],
// Accessibilita
'categories:accessibility': ['error', { minScore: 0.9 }],
// Best Practice
'categories:best-practices': ['warn', { minScore: 0.9 }],
// SEO
'categories:seo': ['error', { minScore: 0.9 }],
// Audit specifici
'uses-text-compression': 'error',
'uses-responsive-images': 'warn',
'render-blocking-resources': 'warn',
'unused-javascript': 'warn',
},
},
upload: {
// Salvare i risultati come file temporanei
target: 'temporary-public-storage',
},
},
};
アサーションにおけるエラーと警告の違い
レベルのあるアサーション error ビルドが失敗し、デプロイメントが妨げられる原因となります。
レベルのあるアサーション warn 警告は生成されますが、パイプラインはブロックされません。
アメリカ合衆国 error 重要なメトリクス (LCP、CLS) の場合 warn メトリクス用
監視する (速度インデックス、最適化されていないリソース)。
4. GitHub アクションとの統合
GitHub Actions パイプラインで Lighthouse CI を実行するための完全なワークフローは次のとおりです。
# .github/workflows/lighthouse.yml
name: Lighthouse CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
lighthouse:
name: Lighthouse Audit
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build production
run: npx ng build --configuration=production
- name: Run Lighthouse CI
uses: treosh/lighthouse-ci-action@v12
with:
configPath: './lighthouserc.js'
uploadArtifacts: true
temporaryPublicStorage: true
- name: Upload Lighthouse reports
uses: actions/upload-artifact@v4
if: always()
with:
name: lighthouse-reports
path: .lighthouseci/
retention-days: 7
静的サーバーを使用した代替構成
より信頼性の高い結果を得るには、静的サーバーを使用して運用ビルドを提供するのが最善です
を使用する代わりに ng serve:
// lighthouserc.js - con server statico
module.exports = {
ci: {
collect: {
numberOfRuns: 5,
url: ['http://localhost:8080/'],
startServerCommand: 'npx http-server dist/my-app/browser -p 8080 -c-1',
startServerReadyPattern: 'Available on',
startServerReadyTimeout: 10000,
settings: {
chromeFlags: '--no-sandbox --headless --disable-gpu',
preset: 'desktop', // oppure 'perf' per mobile simulation
},
},
assert: {
preset: 'lighthouse:recommended',
assertions: {
'categories:performance': ['error', { minScore: 0.9, aggregationMethod: 'median-run' }],
'categories:accessibility': ['error', { minScore: 0.9 }],
'categories:best-practices': ['warn', { minScore: 0.85 }],
'categories:seo': ['error', { minScore: 0.9 }],
},
},
upload: {
target: 'temporary-public-storage',
},
},
};
5. スコアを経時的に追跡する
パフォーマンスの変化を監視するには、履歴スコアを保存すると便利です。灯台 CI はこの目的のために専用サーバーをサポートしています。あるいは、より長いアプローチを使用することもできます GitHub Actions アーティファクトを使用すると簡単です:
- name: Extract Lighthouse scores
id: lh-scores
run: |
# Estrarre i punteggi dal report JSON
REPORT=$(find .lighthouseci -name 'lhr-*.json' | head -1)
PERF=$(jq '.categories.performance.score * 100' "$REPORT")
A11Y=$(jq '.categories.accessibility.score * 100' "$REPORT")
BP=$(jq '.categories["best-practices"].score * 100' "$REPORT")
SEO=$(jq '.categories.seo.score * 100' "$REPORT")
echo "performance=$PERF" >> "$GITHUB_OUTPUT"
echo "accessibility=$A11Y" >> "$GITHUB_OUTPUT"
echo "best-practices=$BP" >> "$GITHUB_OUTPUT"
echo "seo=$SEO" >> "$GITHUB_OUTPUT"
- name: Comment PR with scores
if: github.event_name == 'pull_request'
uses: actions/github-script@v7
with:
script: |
const perf = '${{ steps.lh-scores.outputs.performance }}';
const a11y = '${{ steps.lh-scores.outputs.accessibility }}';
const bp = '${{ steps.lh-scores.outputs.best-practices }}';
const seo = '${{ steps.lh-scores.outputs.seo }}';
const body = `## Lighthouse Scores
| Category | Score |
|----------|-------|
| Performance | ${perf}/100 |
| Accessibility | ${a11y}/100 |
| Best Practices | ${bp}/100 |
| SEO | ${seo}/100 |`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: body
});
6. バンドルサイズの追跡
Lighthouse に加えて、バンドルのサイズを長期的に監視することが重要です。昇給 徐々に進行し、深刻な問題になるまで気付かないことがよくあります。
# Step per monitorare la dimensione del bundle
- name: Analyze bundle size
run: |
# Calcolare la dimensione totale del bundle
TOTAL=$(find dist/my-app/browser -name '*.js' -o -name '*.css' | \
xargs wc -c | tail -1 | awk '{print $1}')
TOTAL_KB=$((TOTAL / 1024))
echo "Bundle totale: ${TOTAL_KB} KB"
# Calcolare la dimensione gzippata
GZIP_TOTAL=0
for file in $(find dist/my-app/browser -name '*.js' -o -name '*.css'); do
SIZE=$(gzip -c "$file" | wc -c)
GZIP_TOTAL=$((GZIP_TOTAL + SIZE))
done
GZIP_KB=$((GZIP_TOTAL / 1024))
echo "Bundle gzippato: ${GZIP_KB} KB"
# Verificare il budget
MAX_GZIP_KB=400
if [ "$GZIP_KB" -gt "$MAX_GZIP_KB" ]; then
echo "ERRORE: Bundle gzippato (${GZIP_KB} KB) supera il budget (${MAX_GZIP_KB} KB)"
exit 1
fi
ビジュアルバンドルアナライザー
バンドル内のスペースを占有しているものを理解するために、Angular には組み込みのビジュアル アナライザーが用意されています。
# Generare le statistiche del bundle
npx ng build --configuration=production --stats-json
# Analizzare con webpack-bundle-analyzer
npx webpack-bundle-analyzer dist/my-app/browser/stats.json
# Alternativa: source-map-explorer per analisi più dettagliata
npx source-map-explorer dist/my-app/browser/main.*.js
7. 代替ツールとの比較
パフォーマンス監視ツール
| 楽器 | タイプ | 料金 | CI統合 | に最適 |
|---|---|---|---|---|
| ライトハウスCI | オープンソース | 無料 | ネイティブ | すべてのプロジェクト |
| スピードカーブ | SaaS | 月額20ドルから | API | 継続的な監視 |
| 口径 | SaaS | 月額 45 ドルから | API | エンタープライズチーム |
| バンドルウォッチ | オープンソース | 無料 | GitHub アプリ | バンドルサイズのみ |
| サイズ制限 | オープンソース | 無料 | npmスクリプト | クイックサイズチェック |
8. 回帰でビルドが失敗する
最も堅牢な構成では、Angular バジェットと Lighthouse CI を組み合わせて、 パフォーマンス低下に対する二重の障壁:
# Pipeline completa con performance gates
name: Performance Pipeline
on:
pull_request:
branches: [main]
jobs:
build-check:
name: Build and Budget Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
# Gate 1: Angular budget check (durante la build)
- name: Build with budget check
run: npx ng build --configuration=production
# La build fallisce se i budget in angular.json sono superati
lighthouse-check:
name: Lighthouse Performance Audit
runs-on: ubuntu-latest
needs: build-check
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npx ng build --configuration=production
# Gate 2: Lighthouse audit (metriche runtime)
- name: Run Lighthouse CI
uses: treosh/lighthouse-ci-action@v12
with:
configPath: './lighthouserc.js'
uploadArtifacts: true
temporaryPublicStorage: true
段階的導入戦略
- 1週目: Lighthouse CI をモードで実行する
warnベースラインを収集する - 2週目: ベースラインに基づいてしきい値を設定します (平均 - 5%)
- 3週目: 重要なメトリクス (LCP、CLS) を渡す
error - 第 4 週: ブランチ保護ルールを有効にして Lighthouse チェックを要求する
- 進行中: チームが最適化するにつれて、しきい値を徐々に厳しくします
結論
この記事では、完全なパフォーマンス監視システムを構築しました。 CI/CD パイプライン内。サイズ制御のためにAngularバジェットを構成しました バンドルの統合、各プルリクエストでの自動監査のための Lighthouse CI の統合、および実装 PR コメントで直接スコアを報告します。
重要なメッセージは、パフォーマンスは他の要件と同様に扱われる必要があるということです。 プロジェクトの: 自動的に定義、測定、検証されます。予算と Lighthouse CI について パイプラインでは、本番環境に到達する前に各回帰が捕捉されます。
シリーズの最後の記事では、 アプリケーションの監視とアラート ウェブ: Sentry によるエラー追跡、実際のユーザーの監視、およびメンテナンス戦略 導入後も高い品質を維持します。







