const config = require('./custom/config'); const options = { logLevel: 'info', output: 'html', onlyCategories: ['performance', 'accessibility', 'best-practices', 'pwa', 'seo'], port: chrome.port, }; const runnerResult = await lighthouse( 'https://goofish.com', options, config // 新增的自定义配置 );传入自定义收集器(gatherer)与审查器(audit)
// main.js const config = require('./custom/config'); // config.js const customResourceGatherer = require('./custom-resource-gatherer'); const customImageAudit = require('./custom-image-audit'); module.exports = { extends: 'lighthouse:default', // 'lighthouse:default' | undefined 是否继承默认配置 settings: { onlyAudits: [ 'custom-image-audit', ], }, passes: [ { passName: 'defaultPass', gatherers: [ customResourceGatherer, // 填入自己的收集器 ] } ], // Object[] 采集器 audits: [ customImageAudit, // 填入自己的审查器 ], categories: { // 这里是在lh报告上的展示的类别配置,和performance seo那些同级 resource: { title: '静态资源', //定义一个叫静态资源的分组,下面规定有哪些审查器 description: '展示页面上的所有资源情况', auditRefs: [ { id: 'custom-image-audit', weight: 1, group: 'metrics' } ] }, }, groups: { // 这里是分组配置,属于类别的下一级 metrics: { title: '资源', }, }, }编写收集器(gatherer)
const Gatherer = require('lighthouse').Gatherer; class CustomResourceGatherer extends Gatherer { beforePass() { // 设定页面加载之前的采集内容 } afterPass(options) { // 设定页面加载之后的采集内容 const driver = options.driver; // 这里通过传入的变量注入自定义js,收集返回 return driver .evaluateAsync( 'JSON.stringify(window.performance.getEntriesByType("resource").filter(item => item.initiatorType === "img" && /(png|apng|gif|webp|jpg|jpeg)$/.test(item.name)))' ) .then((loadMetrics) => { if (!loadMetrics) { throw new Error('无法获取资源信息'); } return loadMetrics; // 返回收集的数据 }); } }
const Audit = require('lighthouse').Audit; class CustomRequestAudit extends Audit { static get meta() { return { id: 'custom-image-audit', // 与配置中的audits数组内容对应 title: '图片请求数据', // 分数达标时的展示标题(score大于等于90分) failureTitle: '资源加载失败', // 分数不达标时的展示标题 description: '展示页面中加载的图片数据', // 子标题 requiredArtifacts: ['CustomResourceGatherer'] // 所对应数据的采集器 }; } static audit(artifacts) { // 获得收集器的数据 const loadMetrics = JSON.parse(artifacts.CustomResourceGatherer); if (!loadMetrics.length) { return { numericValue: 0, score: 1, displayValue: 'No image found' }; } // 整理数据 const data = loadMetrics.map((item) => { return { name: item.name, duration: `${parseInt(item.duration)}ms`, size: item.encodedBodySize } }) const headings = [ { key: 'name', itemType: 'url', text: '请求' }, { key: 'duration', itemType: 'text', text: '耗时' }, { key: 'size', itemType: 'text', text: '大小' } ]; // 根据自定义规则返回得分 return { score: 0.89, // 自定定义分数 // 这里可以使用audit提供的样式展示格式,通过传入数据来控制展示 details: Audit.makeTableDetails(headings, data), displayValue: `页面中有 ${loadMetrics.length} 个图片`, rawValue: '', } }
结果展示