This directory contains useful documentation, examples (read on), and ways to get you started. For an overview of the internal structure of Lighthouse, see The Lighthouse Structure.

Used programmatically

The following example demonstrates how to run Lighthouse programmatically as a Node module. It assumes that you have Lighthouse installed as a dependency (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(); }) ();Copy the code

Using only Performance

Many modules that use Lighthouse are only interested in performance numbers. You can limit the audits you run to a specific category or set of audits.

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

You can also design your own configuration (such as the experimental – configuration file) for custom runs. See also basic custom audit methods.

Differs from CLI flags

Note that certain flag features are only available to the CLI. The shared set of flags that work in Node and CLI can be found in our Typedefs. In most cases, this functionality is not provided in Node modules simply because it is easier and more flexible to do it yourself.

CLI Flag Node difference Port Only specifies the port to use. Chrome does not start it for you. Ignore chromeFlags, Chrome will not start for you. OutputPath is ignored and output is returned as a string in the '. Report 'attribute. SaveAssets are ignored, and the item is returned in the '.Artifacts' property. View ignored. If you need this function, use the 'open' NPM module. EnableErrorReporting is ignored and always disables error reporting for Node. ListAllAudits are ignored and have nothing to do with program use. ListTraceCategories is ignored and has nothing to do with the use of the program. ConfigPath is ignored, config is passed to lighthouse as the third parameter to be ignored, and config is passed to Lighthouse VERBOSE as the third parameter to be ignored, and logLevel is used instead. Quiet Uses logLevel instead of quiet.Copy the code

Enabling Logging

If you want to see log output while Lighthouse is running, set the appropriate logLevel in your code and pass the logLevel flag when you call Lighthouse.

const flags = {logLevel: 'info'}; launchChromeAndRunLighthouse('https://example.com', flags).then(...) ;Copy the code

configuration

To programmatically extend the Lighthouse configuration, you need to pass a Config object as a third parameter. If omitted, the default configuration is used.

Example:

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

You can extend the base configuration from Lighthouse: Default, or you can build your own configuration from scratch to gain full control.

For more information about the types of configurations you can provide, see Lighthouse Configurations.

Test on a site with authentication

Chrome-debug will be added to your PATH when installed globally with NPM I-G Lighthouse or YARN Global Add Lighthouse. This binary starts a separate Instance of Chrome with a debug port open.

  • runchrome-debug. This records the debug port of the Chrome instance
  • Navigate to your site and log in.
  • In a separate terminal TAB, runlighthouse http://mysite.com --port port-numberUse the port number in Chrome-debug.

Use untrusted certificates to test on the site

When you test your site with an untrusted certificate, Chrome won’t load pages, so the Lighthouse report will mostly contain errors.

If this certificate is a certificate that you control and is required for development (for example, a localhost with a self-signed certificate for local HTTP/2 testing), we recommend that you add the certificate to the local trusted certificate store. In Chrome, see Settings > Privacy and Security > Manage Certificates (Settings > Privacy and Security > Manage Certificates) or instructions for adding to the certificate store in your operating system.

Alternatively, you can instruct Chrome to ignore invalid certificates by adding the Lighthouse CLI flag — chrom-flags =”–ignore-certificate-errors”. However, you must be careful with this flag, as it is equivalent to browsing the Web with TLS disabled. Anything that the test page loads (such as third-party scripts or Iframed ads) is also not subject to certificate checking, opening the way for MitM attacks. For these reasons, we recommend using the earlier solution to add certificates to the local certificate store.

Test it on a mobile device

Lighthouse runs on true mobile devices. You can follow step 3.3 with remote debugging (traditional workflow) on Android, but TL; The DR is to install and run ADB, enable USB debugging, and then forward the 9222 from the device port to the machine with Lighthouse.

You might want to use the CLI mark — – emulated – form – factor = none — throttling. CpuSlowdownMultiplier = 1 to disable any other simulations.

$ 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
Copy the code

Lighthouse serves as the tracking processor

Lighthouse can be used to analyze trace and performance data collected from other tools, such as WebgeTest and ChromeDriver. The traces and devtoolsLogs artifact items can be supplied using strings of absolute paths on disk, if they are saved with them. The trace.json file is also available. Json are file extensions, respectively. The devtoolsLogs array is captured from the network and page domains (enableNetwork and enablePage options for la ChromeDriver).

For example, here is a trace-only run that reports user timings and key request chains:

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}
      ]
    }
  }
}
Copy the code

Then, run: ‘lighthouse –config-path=config.json www.random.url

Supplementary provisions

Untranslated part: Using Lighthouse programmatically Parameter description: juejin.cn/post/685733…

`