const fs = require('fs');
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
(async () => {
// 启动 Chrome 浏览器
const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless'] });
// 设置 Lighthouse 的选项
const options = {
logLevel: 'info', // 日志级别为 info,输出详细信息
output: 'html', // 生成 HTML 格式的报告
onlyCategories: ['performance', "accessibility", "best-practices"], // 只检查性能相关的指标
port: chrome.port // 使用 Chrome 实例的端口
};
// 运行 Lighthouse,对指定的网址进行性能检测
const runnerResult = await lighthouse('https://www.baidu.com', options);
// 将生成的报告写入文件
const reportHtml = runnerResult.report;
fs.writeFileSync('lhreport.html', reportHtml);
// 打印 Lighthouse 的结果信息
console.log('Report is done for', runnerResult.lhr.finalUrl);
console.log('Performance score was', runnerResult.lhr.categories.performance.score * 100);
// 关闭 Chrome 浏览器实例
await chrome.kill();
})();
node 运行代码
webpack配置代码
{
"name": "lighthousetest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@babel/core": "^7.19.3",
"@babel/plugin-proposal-decorators": "^7.19.3",
"@babel/register": "^7.18.9",
"babel-preset-env": "^1.7.0",
"chrome-launcher": "^0.14.2",
"fs": "^0.0.1-security",
"lighthouse": "^7.5.0"
}
}
官网示例有头无尾,依赖的版本号也不说~,坑的很。