맞춤 감사 및 단정
프로젝트에 필요한 특정 성능 또는 모범 사례 규칙을 적용하도록 자체 Lighthouse 감사를 개발합니다.
맞춤 감사 및 단정은(는) CoddyKit의 무료 Web Performance Optimization & Lighthouse 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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.
자주 묻는 질문
“맞춤 감사 및 단정” 강의는 무료인가요?
네 — “맞춤 감사 및 단정” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web Performance Optimization & Lighthouse 강의 전체를 잠금 해제할 수 있습니다. Web Performance Optimization & Lighthouse 강의에는 총 4개의 강의가 포함되어 있습니다.
“맞춤 감사 및 단정”에서 뭘 배우나요?
프로젝트에 필요한 특정 성능 또는 모범 사례 규칙을 적용하도록 자체 Lighthouse 감사를 개발합니다. 브라우저에서 직접 실행하는 실습 코드로 Web Performance Optimization & Lighthouse을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Web Performance Optimization & Lighthouse을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Web Performance Optimization & Lighthouse은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“맞춤 감사 및 단정” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Web Performance Optimization & Lighthouse 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Web Performance Optimization & Lighthouse 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.