perf-lighthouse by tech-leads-club/agent-skills
npx skills add https://github.com/tech-leads-club/agent-skills --skill perf-lighthouse# 安装
npm install -g lighthouse
# 基础审计
lighthouse https://example.com
# 仅移动端性能(更快)
lighthouse https://example.com --preset=perf --form-factor=mobile
# 输出 JSON 用于解析
lighthouse https://example.com --output=json --output-path=./report.json
# 输出 HTML 报告
lighthouse https://example.com --output=html --output-path=./report.html
--preset=perf # 仅性能(跳过可访问性、SEO 等)
--form-factor=mobile # 移动设备模拟(默认)
--form-factor=desktop # 桌面设备
--throttling-method=devtools # 更精确的节流
--only-categories=performance,accessibility # 特定类别
--chrome-flags="--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 }
]
}
]
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
使用预算运行:
lighthouse https://example.com --budget-path=./budget.json
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/workflows/lighthouse.yml
name: Lighthouse
on:
pull_request:
push:
branches: [main]
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: 构建站点
run: npm ci && npm run build
- name: 运行 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 }}
用于具有历史追踪功能的完整 CI 集成:
# 安装
npm install -g @lhci/cli
# 初始化配置
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', // 或使用 'lhci' 用于自托管
},
},
}
运行:
lhci autorun
import fs from 'fs'
const report = JSON.parse(fs.readFileSync('./report.json'))
// 总体分数(0-1,乘以 100 得到百分比)
const scores = {
performance: report.categories.performance.score,
accessibility: report.categories.accessibility.score,
seo: report.categories.seo.score,
}
// 核心 Web 指标
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,
}
// 失败的审计项
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 }))
# 保存基线
lighthouse https://prod.example.com --output=json --output-path=baseline.json
# 在 PR 上运行
lighthouse https://preview.example.com --output=json --output-path=pr.json
# 比较(自定义脚本)
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 脚本 |
每周安装量
78
代码仓库
GitHub 星标数
1.9K
首次出现
2026年2月5日
安全审计
安装于
opencode75
gemini-cli72
codex72
github-copilot72
cursor70
amp66
# 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
Create 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 }
]
}
]
Run with budget:
lighthouse https://example.com --budget-path=./budget.json
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/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 }}
For full CI integration with historical tracking:
# Install
npm install -g @lhci/cli
# Initialize config
lhci wizard
Creates 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
},
},
}
Run:
lhci autorun
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
Simple comparison script:
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)})`)
})
| Issue | Solution |
|---|---|
| Inconsistent scores | Run multiple times (--number-of-runs=3), use median |
| Chrome not found | Set CHROME_PATH env var |
| Timeouts | Increase with --max-wait-for-load=60000 |
| Auth required | Use --extra-headers or puppeteer script |
Weekly Installs
78
Repository
GitHub Stars
1.9K
First Seen
Feb 5, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykWarn
Installed on
opencode75
gemini-cli72
codex72
github-copilot72
cursor70
amp66
Skills CLI 使用指南:AI Agent 技能包管理器安装与管理教程
44,900 周安装