Introduction to Lighthouse
Lighthouse is an open-source, automated tool for improving the quality of web pages. You can run it against any web page, public or requiring authentication. It has audits for performance, accessibility, progressive web apps, SEO, and more.
Getting Started with Lighthouse APIs
Here we introduce dozens of useful Lighthouse APIs with code snippets to help you enhance your website’s performance and SEO.
Install Lighthouse
npm install -g lighthouse
Basic Lighthouse Command
lighthouse https://example.com --output html
Using Lighthouse in Node.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: ['performance'] };
const runnerResult = await lighthouse('https://example.com', options);
console.log('Report is done for', runnerResult.lhr.finalUrl);
console.log('Performance score was', runnerResult.lhr.categories.performance.score * 100);
await chrome.kill();
})();
Custom Configuration
module.exports = {
extends: 'lighthouse:default',
settings: {
onlyCategories: ['performance', 'accessibility'],
},
};
Using Lighthouse CI
npm install -g @lhci/cli
lhci autorun
App Example with Lighthouse APIs
Below is an example of a simple Node.js app that uses the Lighthouse API to audit a web page’s performance:
const express = require('express');
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const app = express();
const port = 3000;
app.get('/audit', async (req, res) => {
const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless'] });
const options = { logLevel: 'info', output: 'html', onlyCategories: ['performance'] };
const runnerResult = await lighthouse('https://example.com', options);
const reportHtml = runnerResult.report;
res.send(reportHtml);
await chrome.kill();
});
app.listen(port, () => {
console.log(`Lighthouse app listening at http://localhost:${port}`);
});
Conclusion
Integrating Lighthouse into your development workflow can significantly enhance your website’s performance and SEO, leading to better user experiences and higher search engine rankings. Start using Lighthouse today to take advantage of its powerful auditing capabilities!
Hash: b370de14e94142d4a108a79df6d0e265a0ba3fa2e10f57c4b3a892b74c9f84aa