CLI 및 프로그래밍 방식 Lighthouse
명령줄에서 Lighthouse 감사를 실행하고 그 API를 맞춤형 스크립트와 애플리케이션에 통합하는 방법을 학습합니다.
CLI 및 프로그래밍 방식 Lighthouse은(는) CoddyKit의 무료 Web Performance Optimization & Lighthouse 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web Performance Optimization & Lighthouse 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web Performance Optimization & Lighthouse 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Beyond the Browser
You've likely used Lighthouse in your browser's DevTools. But what if you want to run audits automatically or integrate them into your workflow?
This lesson explores how to use Lighthouse from the command line (CLI) for quick checks and programmatically via its Node.js API for advanced automation.
Automate & Integrate
Running Lighthouse from the CLI or programmatically opens up powerful possibilities:
- Automation: Schedule regular audits without manual intervention.
- CI/CD Integration: Catch performance regressions early in your development pipeline.
- Custom Reports: Generate reports tailored to your specific needs.
- Large-Scale Testing: Audit many pages efficiently across a website.
Get Lighthouse CLI
To use Lighthouse from the command line, you need Node.js installed on your system. Once Node.js is ready, you can install the Lighthouse CLI globally using npm:
npm install -g lighthouse
This command makes the lighthouse command available directly in your terminal, allowing you to run audits from any directory.
Run a Basic CLI Audit
With Lighthouse CLI installed, running an audit is straightforward. Just provide the URL you want to test. By default, it outputs a summary to the console and generates an HTML report.
lighthouse https://www.example.com
This will launch a headless Chrome instance, run the audit, and then generate an HTML report file in your current directory named after the URL.
Choose Your Output
The Lighthouse CLI can generate reports in different formats. You can specify the output type and path using flags:
--output html: Generates a user-friendly HTML report (default).--output json: Provides raw audit data in JSON format for parsing.--output csv: Exports a summary of key metrics as a CSV file.
Try running an audit and saving the output as JSON:
lighthouse https://www.example.com --output json --output-path ./report.json
Customize Your Audit
You can fine-tune your audits with various options to simulate different user conditions or focus on specific aspects:
--throttling-preset: Simulates different network and CPU conditions (e.g.,mobile,desktop).--only-categories: Focuses the audit on specific categories (e.g.,performance,accessibility).
Example: Audit only performance for a desktop user:
lighthouse https://www.example.com --throttling-preset desktop --only-categories performance
Lighthouse as an API
For deeper integration and more control, Lighthouse offers a Node.js API. This allows you to embed Lighthouse directly into your JavaScript applications, giving you full control over the audit process and access to the raw results.
It typically uses Puppeteer, a Node library, to programmatically control a headless Chrome browser instance for the audit.
Basic Programmatic Audit
Let's create a simple Node.js script to run a Lighthouse audit. First, ensure you have lighthouse and chrome-launcher installed in your project:
npm install lighthouse chrome-launcher
Then, create a .js file (e.g., audit.js) with the following code:
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
async function runLighthouseAudit(url) {
// Launch a headless Chrome instance
const chrome = await chromeLauncher.launch({
chromeFlags: ['--headless']
});
// Configure Lighthouse options
const options = {
logLevel: 'info',
output: 'json',
port: chrome.port // Connect to the launched Chrome instance
};
// Run Lighthouse audit
const runnerResult = await lighthouse(url, options);
console.log('Audit complete for %s', runnerResult.lhr.finalUrl);
console.log('Performance score: %s', runnerResult.lhr.categories.performance.score * 100);
// Kill the Chrome instance
await chrome.kill();
}
// Call the function with a URL to audit
runLighthouseAudit('https://www.example.com');Extracting Audit Data
The runnerResult object contains a wealth of data about the audit (lhr stands for Lighthouse Result). You can programmatically access scores, specific audit details, and more.
Here's how to extract the Performance score and First Contentful Paint (FCP) value from the results:
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
async function extractAuditData(url) {
const chrome = await chromeLauncher.launch({
chromeFlags: ['--headless']
});
const options = {
port: chrome.port
};
const runnerResult = await lighthouse(url, options);
// Access the overall performance score
const performanceScore = runnerResult.lhr.categories.performance.score * 100;
// Access a specific audit result by its ID (e.g., First Contentful Paint)
const fcpAudit = runnerResult.lhr.audits['first-contentful-paint'];
console.log(`Performance Score: ${performanceScore}%`);
console.log(`First Contentful Paint: ${fcpAudit.displayValue}`);
await chrome.kill();
}
extractAuditData('https://www.example.com');When to Use What?
You've learned about both CLI and programmatic Lighthouse. Which of the following are ideal use cases for using Lighthouse programmatically (via its Node.js API)?
Recap: CLI & API Power
Great job! You've explored the power of Lighthouse beyond the browser.
- The Lighthouse CLI is perfect for quick, on-demand audits and simple report generation directly from your terminal.
- The Lighthouse Node.js API provides deep integration capabilities, enabling automation, custom reporting, and embedding performance checks into complex applications and workflows.
These tools are essential for maintaining and improving web performance at scale and integrating audits into your development process.
자주 묻는 질문
“CLI 및 프로그래밍 방식 Lighthouse” 강의는 무료인가요?
네 — “CLI 및 프로그래밍 방식 Lighthouse” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web Performance Optimization & Lighthouse 강의 전체를 잠금 해제할 수 있습니다. Web Performance Optimization & Lighthouse 강의에는 총 4개의 강의가 포함되어 있습니다.
“CLI 및 프로그래밍 방식 Lighthouse”에서 뭘 배우나요?
명령줄에서 Lighthouse 감사를 실행하고 그 API를 맞춤형 스크립트와 애플리케이션에 통합하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Web Performance Optimization & Lighthouse을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Web Performance Optimization & Lighthouse을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Web Performance Optimization & Lighthouse은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“CLI 및 프로그래밍 방식 Lighthouse” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Web Performance Optimization & Lighthouse 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Web Performance Optimization & Lighthouse 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- CLI 및 프로그래밍 방식 Lighthouse
- 맞춤 감사 및 단정
- CI/CD에 Lighthouse 통합
- Lighthouse를 활용한 성능 예산