自定义审计与断言
开发自己的 Lighthouse 审计,以强制执行与项目相关的特定性能或最佳实践规则。
自定义审计与断言 是 CoddyKit 上的免费 Web Performance Optimization & Lighthouse 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web Performance Optimization & Lighthouse 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web Performance Optimization & Lighthouse 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Extend Lighthouse's Power
Welcome to creating custom Lighthouse audits! While Lighthouse offers many built-in checks, sometimes you need to enforce project-specific rules or validate unique performance requirements.
This lesson shows you how to build your own.
Why Create Custom Audits?
Custom audits allow you to tailor Lighthouse to your exact needs. They help you:
- Enforce Standards: Check for specific coding patterns or component usage.
- Validate Unique Metrics: Measure performance aspects not covered by default.
- Ensure Compliance: Verify project-specific accessibility or SEO rules.
- Automate Checks: Integrate tailored performance feedback directly into your development workflow.
Audit Anatomy: Gatherers & Audits
A custom Lighthouse audit typically has two main parts:
- Gatherer: This component collects raw data about the page. It runs inside the browser and extracts specific information, like DOM elements, network requests, or JavaScript variables.
- Audit: This component analyzes the data collected by the gatherer. It applies logic to determine a score, a pass/fail state, and provides recommendations.
Both are then linked in a Lighthouse configuration file.
Building a Gatherer: Data Collection
A gatherer is responsible for collecting data. It extends Lighthouse.Gatherer and uses methods like afterPass to run JavaScript in the page's context.
Let's create a gatherer that checks for a specific <meta> tag.
Gatherer Code Example
This gatherer looks for an <meta name="author"> tag and returns its content. If not found, it returns null.
// gatherers/author-meta-gatherer.js
'use strict';
const Gatherer = require('lighthouse').Gatherer;
class AuthorMetaGatherer extends Gatherer {
afterPass(options) {
const driver = options.driver;
// Evaluate JS in the browser context
return driver.evaluateAsync(() => {
const metaTag = document.querySelector('meta[name="author"]');
return metaTag ? metaTag.content : null;
});
}
}
module.exports = AuthorMetaGatherer;Building an Audit: Evaluation Logic
An audit takes the data provided by gatherers and applies your custom logic. It extends Lighthouse.Audit and implements a static audit method.
This method receives the collected "artifacts" (data) and determines the audit's result.
Audit Code Example
This audit uses the data from our AuthorMetaGatherer to check if the author meta tag is present and has content. It scores 1 (pass) or 0 (fail).
// audits/author-meta-audit.js
'use strict';
const Audit = require('lighthouse').Audit;
class AuthorMetaAudit extends Audit {
static get meta() {
return {
id: 'author-meta-tag',
title: 'Author meta tag is present',
failureTitle: 'Author meta tag is missing or empty',
description: 'Ensures an author meta tag is present for attribution.',
requiredArtifacts: ['AuthorMetaGatherer'],
};
}
static audit(artifacts) {
const authorMetaContent = artifacts.AuthorMetaGatherer;
const passed = !!authorMetaContent && authorMetaContent.trim().length > 0;
return {
score: passed ? 1 : 0,
details: {
type: 'debuginfo',
headings: [
{key: 'content', itemType: 'text', text: 'Author Meta Content'},
],
items: [{content: authorMetaContent || 'Not found'}],
},
};
}
}
module.exports = AuthorMetaAudit;Integrating into Lighthouse Config
To make Lighthouse aware of your custom gatherer and audit, you need a custom configuration file. This file tells Lighthouse which gatherers to run and which audits to include, often extending the default Lighthouse checks.
// custom-config.js
'use strict';
module.exports = {
extends: 'lighthouse:default', // Inherit default audits
gatherers: [
'./gatherers/author-meta-gatherer.js',
],
audits: [
'./audits/author-meta-audit.js',
],
categories: {
'custom-category': {
title: 'Custom Checks',
description: 'Project-specific performance and best practice audits.',
auditRefs: [
{id: 'author-meta-tag', weight: 1, group: 'metrics'},
],
},
},
};Running Lighthouse with Custom Audits
Finally, you can run Lighthouse programmatically using Node.js, referencing your custom configuration file. This script launches Chrome, runs Lighthouse, and generates a report.
Make sure you have lighthouse and chrome-launcher installed via npm.
// run-custom-audit.js
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
(async () => {
const chrome = await chromeLauncher.launch({chromeFlags: ['--headless']});
const options = {
logLevel: 'info',
output: 'html',
onlyCategories: ['custom-category'], // Run ONLY our custom category
port: chrome.port
};
const config = require('./custom-config.js'); // Load your custom config
const runnerResult = await lighthouse('https://example.com', options, config);
console.log('Report is done for', runnerResult.lhr.requestedUrl);
// Accessing your custom audit score:
const customAuditScore = runnerResult.lhr.audits['author-meta-tag'].score;
console.log('Author Meta Tag Audit Score:', customAuditScore);
await chrome.kill();
})();Custom Audit Components
You've learned about the key pieces needed to build a custom Lighthouse audit.
Which of the following are essential components when creating a custom Lighthouse audit?
Recap: Your Custom Audit Toolkit
You've successfully learned how to extend Lighthouse's capabilities!
By understanding gatherers, audits, and custom configurations, you can now build powerful, project-specific checks. This allows you to enforce unique best practices and gain deeper, tailored insights into your web performance.
用 AI 导师学习 Web Performance Optimization & Lighthouse — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「自定义审计与断言」课时是免费的吗?
是的 — 「自定义审计与断言」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web Performance Optimization & Lighthouse 课程的其余内容,请升级到 CoddyKit PRO。 Web Performance Optimization & Lighthouse 课程共包含 4 节课。
「自定义审计与断言」这节课中我会学到什么?
开发自己的 Lighthouse 审计,以强制执行与项目相关的特定性能或最佳实践规则。 你通过在浏览器中直接运行的动手代码来练习 Web Performance Optimization & Lighthouse,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Web Performance Optimization & Lighthouse 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Web Performance Optimization & Lighthouse 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「自定义审计与断言」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Web Performance Optimization & Lighthouse 课中编写并运行代码吗?
能。每节 Web Performance Optimization & Lighthouse 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。