Библиотека Lighthouse предоставляет удобный программный API для интеграции в серверные и автоматизированные процессы. Основным способом является запуск через Node.js:
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
(async () => {
const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless'] });
const options = { port: chrome.port, output: 'json' };
const runnerResult = await lighthouse('https://example.com', options);
const reportJson = runnerResult.report;
console.log(JSON.parse(reportJson));
await chrome.kill();
})();
Ключевые моменты интеграции с Node.js:
json,
html и csv. JSON используется для последующей
обработки другими инструментами.Lighthouse активно применяется для контроля качества веб-приложений на этапе непрерывной интеграции. Типичный сценарий:
npm install --save-dev lighthouse chrome-launcherПример проверки производительности в Jenkins или GitHub Actions:
- name: Run Lighthouse
run: |
npx lighthouse https://example.com --output json --output-path ./lighthouse-report.json
- name: Check Performance Score
run: |
SCORE=$(jq '.categories.performance.score' ./lighthouse-report.json)
if (( $(echo "$SCORE < 0.9" | bc -l) )); then
echo "Performance threshold not met"
exit 1
fi
Особенности CI/CD интеграции:
thresholds) для
fail-fast стратегии.Puppeteer и Lighthouse совместимы для глубокой кастомизации анализа:
const puppeteer = require('puppeteer');
const lighthouse = require('lighthouse');
const { URL } = require('url');
(async () => {
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.goto('https://example.com');
const { port } = new URL(browser.wsEndpoint());
const result = await lighthouse('https://example.com', { port: port });
console.log(result.lhr.categories.performance.score);
await browser.close();
})();
Преимущества такого подхода:
Lighthouse-отчеты легко интегрируются с инструментами визуализации и мониторинга:
Пример передачи метрик в Prometheus через Node.js:
const { Registry, Gauge } = require('prom-client');
const registry = new Registry();
const performanceGauge = new Gauge({
name: 'lighthouse_performance_score',
help: 'Lighthouse Performance Score',
registers: [registry]
});
const result = JSON.parse(fs.readFileSync('./lighthouse-report.json'));
performanceGauge.set(result.categories.performance.score * 100);
При интеграции с другими инструментами важно учитывать возможность кастомизации:
performance, seo,
accessibility) анализировать.Пример настройки категорий:
const options = {
onlyCategories: ['performance', 'seo'],
port: chrome.port
};
const runnerResult = await lighthouse('https://example.com', options);
Для профессионального мониторинга используется скрипт, который сравнивает текущие результаты с базовыми:
const previousReport = require('./baseline.json');
const currentReport = require('./current.json');
const delta = currentReport.categories.performance.score - previousReport.categories.performance.score;
if (delta < 0) {
console.warn(`Performance regression detected: ${delta}`);
}
Это позволяет:
Эти возможности делают Lighthouse не только инструментом анализа, но и полноценным компонентом DevOps-процессов, позволяющим поддерживать качество веб-приложений на постоянной основе.