如何以Node.js模块方式为Lighthouse程序化添加网络节流
如何在Lighthouse中添加不同网络节流条件并获取Web Vitals指标
要测试Slow 3G、Fast 4G等不同网络环境下的Web Vitals(FCP、LCP、TBT),你可以直接在Lighthouse配置中指定预设的网络节流规则,或者自定义参数。下面是修改后的代码,支持批量测试多种网络条件,并自动保存对应报告、输出关键指标:
const fs = require('fs'); const lighthouse = require('lighthouse'); const chromeLauncher = require('chrome-launcher'); const HOME_PAGE_URL = 'http://localhost:4000'; // 定义需要测试的网络节流配置,包含预设和自定义选项 const networkProfiles = [ { name: 'fast-4g', throttling: { preset: 'fast-4g' } }, { name: 'slow-3g', throttling: { preset: 'slow-3g' } }, // 也可以自定义网络参数,比如模拟2G { name: 'custom-2g', throttling: { rttMs: 1400, throughputKbps: 700, requestLatencyMs: 1400, downloadThroughputKbps: 700, uploadThroughputKbps: 500 } } ]; (async () => { // 启动Chrome实例,复用实例提升效率 const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless', '--no-sandbox'] }); for (const profile of networkProfiles) { try { const options = { logLevel: 'info', output: 'html', onlyCategories: ['performance'], port: chrome.port, // 应用当前网络节流配置 throttling: profile.throttling }; const runnerResult = await lighthouse(HOME_PAGE_URL, options); const reportHtml = runnerResult.report; // 按网络条件命名报告文件 fs.writeFileSync(`lhreport-${profile.name}.html`, reportHtml); // 提取Web Vitals关键指标 const lhr = runnerResult.lhr; const metrics = { FCP: lhr.audits['first-contentful-paint'].displayValue, LCP: lhr.audits['largest-contentful-paint'].displayValue, TBT: lhr.audits['total-blocking-time'].displayValue, performanceScore: lhr.categories.performance.score * 100 }; console.log(`=== ${profile.name} 测试结果 ===`); console.log('测试地址:', lhr.finalDisplayedUrl); console.log('性能得分:', metrics.performanceScore); console.log('FCP:', metrics.FCP); console.log('LCP:', metrics.LCP); console.log('TBT:', metrics.TBT); console.log('------------------------'); } catch (error) { console.error(`测试${profile.name}时出错:`, error.message); } } await chrome.kill(); })();
关键说明:
- 预设节流配置:Lighthouse内置了
fast-4g、slow-3g、no-throttling三种预设,直接通过preset字段调用即可。 - 自定义节流:如果需要模拟特定网络(比如2G),可以手动设置
rttMs(往返延迟)、throughputKbps(吞吐量)等参数。 - 批量测试:通过循环遍历网络配置数组,一次性完成多环境测试,每个环境生成独立的HTML报告。
- 指标提取:从
runnerResult.lhr.audits中直接获取FCP、LCP、TBT的显示值和性能得分,方便对比分析。
使用方式:
- 确保已安装依赖:
npm install lighthouse chrome-launcher - 运行代码:
node your-script-name.js - 查看结果:生成的
lhreport-{profile-name}.html文件可直接在浏览器打开,控制台也会输出关键指标的简洁结果。
内容的提问来源于stack exchange,提问作者KnightCrawler
相关产品推荐
相关产品推荐

