CLI 与编程方式使用 Lighthouse
学习从命令行运行 Lighthouse 审计,并将其 API 集成到自定义脚本和应用中。
CLI 与编程方式使用 Lighthouse 是 CoddyKit 上的免费 Web Performance Optimization & Lighthouse 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web Performance Optimization & Lighthouse 课程的其余内容,请升级到 CoddyKit PRO。 Web Performance Optimization & Lighthouse 课程共包含 4 节课。
「CLI 与编程方式使用 Lighthouse」这节课中我会学到什么?
学习从命令行运行 Lighthouse 审计,并将其 API 集成到自定义脚本和应用中。 你通过在浏览器中直接运行的动手代码来练习 Web Performance Optimization & Lighthouse,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Web Performance Optimization & Lighthouse 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Web Performance Optimization & Lighthouse 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「CLI 与编程方式使用 Lighthouse」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Web Performance Optimization & Lighthouse 课中编写并运行代码吗?
能。每节 Web Performance Optimization & Lighthouse 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- CLI 与编程方式使用 Lighthouse
- 自定义审计与断言
- 将 Lighthouse 集成到持续集成和持续部署中
- 使用 Lighthouse 设置性能预算