使用 npm 安装 Lighthouse 命令行工具:
npm install -g lighthouse
基本使用
在命令行中运行 Lighthouse:
lighthouse https://example.com
生成详细报告
通过指定参数生成包含具体类别的详细报告:
lighthouse https://example.com --only-categories=performance,seo --output=json --output-path=./report.json
集成 CI/CD
在 CI/CD 流程中集成 Lighthouse 以自动化网页质量监控,例如在 GitHub Actions 中:
name: Lighthouse CI
on: [push]
jobs:
lighthouse-ci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Install Lighthouse
run: npm install -g lighthouse
- name: Run Lighthouse
run: lighthouse https://example.com --output=json --output-path=./report.json
lighthouse(url, flags, config):运行 Lighthouse 审计。
url
:要审计的网页 URL。flags
:指定审计参数,如输出格式、报告路径等。config
:自定义审计配置。const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
(async () => {
const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless'] });
const options = { logLevel: 'info', output: 'json', onlyCategories: ['performance'] };
const runnerResult = await lighthouse('https://example.com', options);
// 使用 runnerResult 处理审计结果
console.log(runnerResult.lhr);
await chrome.kill();
})();
chromeLauncher.launch(options):启动 Chrome 浏览器实例。
options
:指定 Chrome 启动参数,如是否启用无头模式。const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless'] });
lighthouse.runnerResult.lhr:获取 Lighthouse 审计报告的 JSON 结果。
lhr
:Lighthouse 报告对象,包含所有审计结果和评分。console.log(runnerResult.lhr);
自定义配置
通过自定义配置文件调整 Lighthouse 的审计行为:
{
"extends": "lighthouse:default",
"settings": {
"onlyCategories": ["performance", "accessibility"],
"throttlingMethod": "devtools",
"emulatedFormFactor": "desktop"
}
}
在命令行中使用自定义配置文件:
lighthouse https://example.com --config-path=./custom-config.js
与 Puppeteer 集成
使用 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');
// 模拟用户交互
await page.click('#some-button');
const { lhr } = await lighthouse(page.url(), {
port: (new URL(browser.wsEndpoint())).port,
output: 'html',
onlyCategories: ['performance']
});
console.log(lhr);
await browser.close();
})();
集成报告
使用 Lighthouse CI 进行自动化报告集成和存储:
npm install -g @lhci/cli
lhci autorun