为您的渐进式 Web 应用程序自动执行 Lighthouse 审计
我们都知道,在开发 Web 应用程序时,Lighthouse 审计提供的洞察信息非常重要且实用。但大多数人检查的方式是通过 Chrome 开发者工具或 Lighthouse 扩展程序手动完成,在我看来,这种方式效率不高。
对于不了解的人来说,使用 Lighthouse 审核 Web 应用程序主要有四种方法:
-
Chrome 开发者工具
-
命令行
-
NPM 模块(我们稍后会用到)
为了以编程方式执行 Lighthouse 审计,我们将使用lighthouse npm 包、mocha和chai来编写我们的测试,并使用chrome-launcher来运行我们的 Lighthouse 测试。
首先,让我们将上述软件包作为开发依赖项安装到我们的项目中:
npm install lighthouse chrome-launcher chai mocha --save-dev
现在,让我们lighthouse.tests.js在tests目录中创建一个名为 `.py` 的文件。我们将通过这个文件运行 Lighthouse 审计。
在这里,我们将导入 Lighthouse 模块和 Chrome 启动器——这将使我们能够从本地开发服务器打开网页,并运行审计,以测试 Lighthouse 分数是否达到我们设定的最低阈值。
虽然这听起来工作量很大,但其实并不多。以下是实际代码示例:
const lighthouse = require("lighthouse");
const chromeLauncher = require("chrome-launcher");
function launchChromeAndRunLighthouse(url, opts, conf = null) {
return chromeLauncher
.launch({ chromeFlags: opts.chromeFlags })
.then(chrome => {
opts.port = chrome.port;
return lighthouse(url, opts, conf).then(res =>
chrome.kill().then(() => res.lhr)
);
});
}
就这么简单。我们使用chromeLauncher.launch方法启动 Chrome 浏览器实例,然后使用网站 URL 和配置运行 Lighthouse 测试以进行审计。测试完成后,我们关闭/终止 Chrome 实例并返回结果。使用方法如下:
launchChromeAndRunLighthouse(testUrl, opts, config).then(res => {
// Results are available in `res`
});
现在,我们可以将这个调用放在before测试的钩子函数中,然后为每个指标编写测试,就像这样:
describe("Lighthouse Audits", function() {
// Timeout doesn't need to be same. It can be more or less depending on your project.
this.timeout(50000);
let results;
before("run test", done => {
launchChromeAndRunLighthouse(testUrl, opts, config).then(res => {
// Extract the results you need for your assertions.
done();
});
});
it("performance test", done => {
// test your performance score against the threshold
done();
});
// Some more tests..
});
看起来还是很奇怪?别担心!看看这个仓库,里面有使用 Mocha 设置 Lighthouse 测试的示例,然后把它应用到你的 Web 应用程序中试试!
(您可以通过此链接找到相关项目列表,其中包括一个使用 Jest 的示例)
该方法可用于在持续集成/部署环境中自动化测试,这样您就不必担心手动审核您的 Web 应用程序并检查它是否达到最低满意水平。
好了,就是这样。这就是我们实现渐进式 Web 应用程序 Lighthouse 审计自动化所需的一切,以确保它们始终符合互联网和用户数据包的安全要求!
感谢阅读! 😄
您也可以通过推特联系我。
祝你编程愉快!干杯!🎉
文章来源:https://dev.to/rishikc/automate-lighthouse-audits-for-your-progressive-web-application-3lfc