以编程方式使用lighthouse(翻译)

1,072 阅读5分钟

这个目录包含有用的文档、示例(继续阅读)和指导您入门的方法。有关lighthouse内部结构的概述,请参见lighthouse结构。

以编程方式使用

下面的示例演示如何以编程方式将Lighthouse作为Node模块运行。它假设您已安装Lighthouse作为依赖项(yarn add --dev lighthouse).

const fs = require('fs');
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'], port: chrome.port};
  const runnerResult = await lighthouse('https://example.com', options);

  // `.report` is the HTML report as a string
  const reportHtml = runnerResult.report;
  fs.writeFileSync('lhreport.html', reportHtml);

  // `.lhr` is the Lighthouse Result as a JS object
  console.log('Report is done for', runnerResult.lhr.finalUrl);
  console.log('Performance score was', runnerResult.lhr.categories.performance.score * 100);

  await chrome.kill();
})();

仅仅使用 Performance

许多使用lighthouse的模块只对性能数字感兴趣。可以将运行的审核限制为特定类别或审核集。

const flags = {onlyCategories: ['performance']};
launchChromeAndRunLighthouse(url, flags).then( // ...

你也可以设计你自己的配置(例如实验性的-配置文件)用于自定义运行。另请参阅基本自定义审核方法

与CLI标志的区别

请注意,某些标志功能仅对CLI可用。在我们的typedefs中可以找到在node和CLI中工作的共享标志集。在大多数情况下,Node模块中不提供该功能,只是因为它更容易和更灵活地自己做。

CLI Flag		Node差异
port			只指定使用哪个端口,Chrome不会为您启动。
chromeFlags		忽略,Chrome不会为你启动。
outputPath		忽略,输出在`.report`属性中以字符串形式返回。
saveAssets		忽略,将在`.artifacts`属性中返回项目。
view			忽略,如果需要此功能,请使用`open` npm模块。
enableErrorReporting
				忽略,始终为Node禁用错误报告。
listAllAudits	忽略,与程序使用无关。
listTraceCategories
				忽略,与程序使用无关。
configPath		忽略,将config作为第三个参数传递给lighthouse
preset			忽略,将config作为第三个参数传递给lighthouse
verbose			忽略,改用logLevel。
quiet			忽略,改用logLevel。

打开日志记录

如果希望在Lighthouse运行时查看日志输出,请在代码中设置适当的日志级别,并在调用Lighthouse时传递logLevel标志。

const flags = {logLevel: 'info'};

launchChromeAndRunLighthouse('https://example.com', flags).then(...);

配置

为了以编程方式扩展Lighthouse配置,需要将config对象作为第三个参数传递。如果省略,则使用默认配置。

示例:

{
  extends: 'lighthouse:default',
  settings: {
    onlyAudits: [
      'first-meaningful-paint',
      'speed-index',
      'first-cpu-idle',
      'interactive',
    ],
  },
}

您可以从lighthouse:default扩展基本配置,或者您可以从头开始构建自己的配置以获得完全的控制权。

有关您可以提供的配置类型的更多信息,请参阅Lighthouse配置

在具有身份验证的站点上进行测试

当通过npm i -g lighthouseyarn global add lighthouse全局安装时,chrome-debug将添加到您的PATH中。这个二进制文件启动一个独立的Chrome实例,其中有一个打开的调试端口。

  • 运行chrome-debug。这将记录Chrome实例的调试端口
  • 导航到您的站点并登录。
  • 在单独的终端选项卡中,运行lighthouse http://mysite.com --port port-number使用chrome-debug中的端口号。

使用不可信证书在站点上测试

当使用不可信的证书测试站点时,Chrome将无法加载页面,因此Lighthouse报告将主要包含错误。

如果此证书是您控制的证书,并且是开发所必需的(例如,具有用于本地HTTP/2测试的自签名证书的localhost),我们建议您将该证书添加到本地受信任的证书存储中。在Chrome中,请参阅“设置”>“隐私和安全”>“管理证书”(Settings > Privacy and Security > Manage certificates),或参阅操作系统中添加到证书存储的说明。

或者,您可以通过添加Lighthouse CLI标志--chrome-flags="--ignore-certificate-errors"指示Chrome忽略无效证书。但是,您必须小心使用此标志,因为它相当于在禁用TLS的情况下浏览web。测试页面加载的任何内容(例如第三方脚本或iframed广告)也不会接受证书检查,从而为MitM攻击开辟了途径。出于这些原因,我们建议使用早期的解决方案,将证书添加到本地证书存储。

在移动设备上测试

lighthouse可以运行在真正的移动设备。您可以按照Android上的远程调试(传统工作流)进行步骤3.3,但是TL;DR是安装并运行adb,启用USB调试,然后将9222从设备端口转发到带有Lighthouse的机器。

您可能希望使用CLI标志——--emulated-form-factor=none --throttling.cpuSlowdownMultiplier=1禁用任何其他模拟。

$ adb kill-server

$ adb devices -l
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
00a2fd8b1e631fcb       device usb:335682009X product:bullhead model:Nexus_5X device:bullhead

$ adb forward tcp:9222 localabstract:chrome_devtools_remote

$ lighthouse --port=9222 --emulated-form-factor=none --throttling.cpuSlowdownMultiplier=1 https://example.com

Lighthouse 作为跟踪处理器

Lighthouse可用于分析从其他工具(如webgetest和ChromeDriver)收集的跟踪和性能数据。traces和devtoolsLogs工件项可以使用磁盘上绝对路径的字符串来提供,如果它们与一起保存的话。trace.json文件还有。devtoolslog.json分别是文件扩展名。devtoolsLogs数组是从网络和页面域(la ChromeDriver的enableNetwork和enablePage选项)捕获的。

例如,下面是一个只跟踪的运行,它报告用户计时和关键请求链:

config.json:

{
  "settings": {
    "auditMode": "/User/me/lighthouse/lighthouse-core/test/fixtures/artifacts/perflog/",
  },
  "audits": [
    "user-timings",
    "critical-request-chains"
  ],

  "categories": {
    "performance": {
      "name": "Performance Metrics",
      "description": "These encapsulate your web app's performance.",
      "audits": [
        {"id": "user-timings", "weight": 1},
        {"id": "critical-request-chains", "weight": 1}
      ]
    }
  }
}

然后,运行:`lighthouse --config-path=config.json www.random.url

附则

非翻译部分: 以编程方式使用Lighthouse参数说明 :juejin.cn/post/685733…

`