Automated auditing, performance metrics, and best practices for the web.
Перейти к файлу
Eric Bidelman 4e08d0f1a4 Offline audit: add warning if initial url != final url (#1919)
* Offline audit: add warning if initial url != final url

* feedback
2017-03-28 10:58:25 -07:00
assets CWS Promo images (#1526) 2017-01-25 11:14:40 -08:00
docs README: Reorganization and new "Using programmatically" section (#1721) 2017-02-15 10:21:25 -08:00
gulp remove formatters 2017-03-09 20:33:33 -08:00
lighthouse-cli CLI: remove npm prepublish (#1889) 2017-03-27 18:24:09 -07:00
lighthouse-core Offline audit: add warning if initial url != final url (#1919) 2017-03-28 10:58:25 -07:00
lighthouse-extension fix: default(.json -> .js). Disable css usage audit (#1911) 2017-03-27 17:29:36 -07:00
lighthouse-viewer remove formatters 2017-03-09 20:33:33 -08:00
typings update jsconfig for intellisense. 2016-12-16 00:27:07 -08:00
.appveyor.yml Rename "appveyor.yml" to ".appveyor.yml". (#1850) 2017-03-13 16:02:41 +11:00
.editorconfig editorconfig 2016-03-09 23:42:40 -08:00
.eslintignore remove formatters 2017-03-09 20:33:33 -08:00
.eslintrc.js use rest parameters instead of arguments (#1524) 2017-01-26 15:52:47 -08:00
.gitattributes Added Windows 10 without Chrome Canary support (#690) 2016-09-22 03:10:17 -07:00
.gitignore remove formatters 2017-03-09 20:33:33 -08:00
.npmignore adjust npmignore. ref #1849 2017-03-24 17:41:51 -07:00
.travis.yml Adopt handlebars precompiled templates (#1752) 2017-03-03 16:57:03 -08:00
AUTHORS authors file. 2016-03-02 15:42:48 -05:00
CONTRIBUTING.md Update CONTRIBUTING.md 2017-03-24 12:50:18 -07:00
LICENSE Adds tests. 2016-01-15 17:13:20 +00:00
gulpfile.js Adopt handlebars precompiled templates (#1752) 2017-03-03 16:57:03 -08:00
jsconfig.json Fix screenshot capture bounds (#1839) 2017-03-08 18:32:20 -08:00
package.json CLI: remove npm prepublish (#1889) 2017-03-27 18:24:09 -07:00
readme.md fix: default(.json -> .js). Disable css usage audit (#1911) 2017-03-27 17:29:36 -07:00
yarn.lock Fixes #1907 - move update-notifier to root (#1908) 2017-03-24 18:11:53 -07:00

readme.md

Lighthouse Build Status Build Status Windows Coverage Status

Lighthouse analyzes web apps and web pages, collecting modern performance metrics and insights on developer best practices.

Lighthouse requires Chrome 56 or later.

Installation

Chrome extension

Install from the Chrome Web Store

Node CLI NPM lighthouse package

Requires Node v6+.

npm install -g lighthouse
# or use yarn:
# yarn global add lighthouse

Running Lighthouse

Chrome extension

Check out the quick-start guide: http://bit.ly/lighthouse-quickstart

CLI

Kick off a run by passing lighthouse the URL to audit:

lighthouse https://airhorner.com/

By default, Lighthouse writes the report to an HTML file. You can control the output format by passing flags.

CLI options

$ lighthouse --help

lighthouse <url>

Logging:
  --verbose  Displays verbose logging                                                      [boolean]
  --quiet    Displays no progress or debug logs                                            [boolean]

Configuration:
  --disable-device-emulation    Disable device emulation                                   [boolean]
  --disable-cpu-throttling      Disable cpu throttling                                     [boolean]
  --disable-network-throttling  Disable network throttling                                 [boolean]
  --save-assets                 Save the trace contents & screenshots to disk              [boolean]
  --save-artifacts              Save all gathered artifacts to disk                        [boolean]
  --list-all-audits             Prints a list of all available audits and exits            [boolean]
  --list-trace-categories       Prints a list of all required trace categories and exits   [boolean]
  --config-path                 The path to the config JSON.
  --perf                        Use a performance-test-only configuration                  [boolean]
  --port                        The port to use for the debugging protocol. Use 0 for a
                                random port.                                         [default: 9222]
  --max-wait-for-load           The timeout (in milliseconds) to wait before the page is
                                considered done loading and the run should continue.
                                WARNING: Very high values can lead to large traces and
                                instability.                                        [default: 25000]

Output:
  --output       Reporter for the results, supports multiple values
                                    [choices: "json", "html"]                      [default: "html"]
  --output-path  The file path to output the results. Use 'stdout' to write to
                 stdout.
                 If using JSON output, default is stdout.
                 If using HTML output, default is a file in the working
                 directory with a name based on the test URL and date.
                 If using multiple outputs, --output-path is ignored.
                 Example: --output-path=./lighthouse-results.html                [default: "stdout"]

Options:
  --help             Show help                                                             [boolean]
  --version          Show version number                                                   [boolean]
  --skip-autolaunch  Skip autolaunch of Chrome when accessing port 9222 fails              [boolean]
  --select-chrome    Interactively choose version of Chrome to use when multiple
                     installations are found                                               [boolean]
Output Examples

lighthouse generates

  • ./<HOST>_<DATE>.report.html

lighthouse --output json generates

  • json output on stdout

lighthouse --output html --output-path ./report.html generates

  • ./report.html

NOTE: specifying an output path with multiple formats ignores your specified extension for ALL formats

lighthouse --output json --output html --output-path ./myfile.json generates

  • ./myfile.report.json
  • ./myfile.report.html

lighthouse --output json --output html generates

  • ./<HOST>_<DATE>.report.json
  • ./<HOST>_<DATE>.report.html

lighthouse --output-path=~/mydir/foo.out --save-assets generates

  • ~/mydir/foo.report.html
  • ~/mydir/foo-0.trace.json
  • ~/mydir/foo-0.screenshots.html

lighthouse --output-path=./report.json --output json --save-artifacts generates

  • ./report.json
  • ./report.artifacts.log

lighthouse --save-artifacts generates

  • ./<HOST>_<DATE>.report.html
  • ./<HOST>_<DATE>.artifacts.log

Testing on a site with authentication

  • chrome-debug
  • open and login to your site
  • lighthouse http://mysite.com

Testing on a mobile device

Lighthouse can run against a real mobile device. You can follow the Remote Debugging on Android (Legacy Workflow) up through step 3.3, but the TL;DR is install & run adb, enable USB debugging, then port forward 9222 from the device to the machine with Lighthouse.

You'll likely want to use the CLI flags --disable-device-emulation --disable-cpu-throttling and potentially --disable-network-throttling.

$ 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 --disable-device-emulation --disable-cpu-throttling https://mysite.com

Using programmatically

The example below shows how to setup and run Lighthouse programmatically as a Node module. It assumes you've installed Lighthouse as a dependency (yarn add --dev lighthouse).

const Lighthouse = require('lighthouse');
const ChromeLauncher = require('lighthouse/lighthouse-cli/chrome-launcher.js').ChromeLauncher;
const Printer = require('lighthouse/lighthouse-cli/printer');

function launchChromeAndRunLighthouse(url, flags, config) {
  const launcher = new ChromeLauncher({port: 9222, autoSelectChrome: true});

  return launcher.isDebuggerReady()
    .catch(() => {
      if (flags.skipAutolaunch) {
        return;
      }
      return launcher.run(); // Launch Chrome.
    })
    .then(() => Lighthouse(url, flags, config)) // Run Lighthouse.
    .then(results => launcher.kill().then(() => results)) // Kill Chrome and return results.
    .catch(err => {
      // Kill Chrome if there's an error.
      return launcher.kill().then(() => {
        throw err;
      }, console.error);
    });
}

// Use an existing config or create a custom one.
const config = require('lighthouse/lighthouse-core/config/perf.json');
const url = 'https://example.com';
const flags = {output: 'html'};

launchChromeAndRunLighthouse(url, flags, config).then(lighthouseResults => {
  lighthouseResults.artifacts = undefined; // You can save the artifacts separately if so desired
  return Printer.write(lighthouseResults, flags.output);
}).catch(err => console.error(err));

Example - extracting an overall score from all scored audits

function getOverallScore(lighthouseResults) {
  const scoredAggregations = lighthouseResults.aggregations.filter(a => a.scored);
  const total = scoredAggregations.reduce((sum, aggregation) => sum + aggregation.total, 0);
  return (total / scoredAggregations.length) * 100;
}

Viewing a report

Lighthouse can produce a report as JSON, HTML, or stdout CLI output.

HTML report:

image

Default CLI output:

image

Online Viewer

Running Lighthouse with the --output=json flag generates a json dump of the run. You can view this report online by visiting https://googlechrome.github.io/lighthouse/viewer/ and dragging the file onto the app. You can also use the "Export" button from the top of any Lighthouse HTML report and open the report in the Lighthouse Viewer.

In the Viewer, reports can be shared by clicking the share icon in the top right corner and signing in to GitHub.

Note: shared reports are stashed as a secret Gist in GitHub, under your account.

Develop

Setup

git clone https://github.com/GoogleChrome/lighthouse

cd lighthouse
npm install
npm run install-all
gulp # to precompile the handlebar templates.

# The CLI is authored in TypeScript and requires compilation.
# If you need to make changes to the CLI, run the TS compiler in watch mode:
# cd lighthouse-cli && npm run dev

See Contributing for more information.

Run

node lighthouse-cli http://example.com

Getting started tip: node --inspect --debug-brk lighthouse-cli http://example.com to open up Chrome DevTools and step through the entire app. See Debugging Node.js with Chrome DevTools for more info.

Creating custom audits & gatherers

The audits and gatherers checked into the lighthouse repo are available to any configuration. If you're interested in writing your own audits or gatherers, you can use them with Lighthouse without necessarily contributing upstream.

Better docs coming soon, but in the meantime look at PR #593, and the tests valid-custom-audit.js and valid-custom-gatherer.js. If you have questions, please file an issue and we'll help out!

Tip: see Lighthouse Architecture for more information on Audits and Gatherers.

Custom configurations for runs

You can supply your own run configuration to customize what audits you want details on. Copy the default.js and start customizing. Then provide to the CLI with lighthouse --config-path=myconfig.js <url>

If you are simply adding additional audits/gatherers or tweaking flags, you can extend the default configuration without having to copy the default and maintain it. Passes with the same name will be merged together, all other arrays will be concatenated, and primitive values will override the defaults. See the example below that adds a custom gatherer to the default pass and an audit.

{
  "extends": true,
  "passes": [
    {
      "passName": "defaultPass",
      "gatherers": ["path/to/custom/gatherer.js"]
    }
  ],
  "audits": ["path/to/custom/audit.js"],
  "aggregations": [
    {
      "name": "Custom Section",
      "description": "Enter description here.",
      "scored": false,
      "categorizable": false,
      "items": [
        {
          "name": "My Custom Audits",
          "audits": {
            "name-of-custom-audit": {}
          }
        }
      ]
    }
  ]
}

Tests

Some basic unit tests forked are in /test and run via mocha. eslint is also checked for style violations.

# lint and test all files
npm test

# watch for file changes and run tests
#   Requires http://entrproject.org : brew install entr
npm run watch

## run linting and unit tests separately
npm run lint
npm run unit

Lighthouse as trace processor

Lighthouse can be used to analyze trace and performance data collected from other tools (like WebPageTest and ChromeDriver). The traces and performanceLog artifact items can be provided using a string for the absolute path on disk. The perf log is captured from the Network domain (a la ChromeDriver's enableNetwork option) and reformatted slightly. As an example, here's a trace-only run that's reporting on user timings and critical request chains:

config.json

{
  "audits": [
    "user-timings",
    "critical-request-chains"
  ],

  "artifacts": {
    "traces": {
      "defaultPass": "/User/me/lighthouse/lighthouse-core/test/fixtures/traces/trace-user-timings.json"
    },
    "performanceLog": "/User/me/lighthouse/lighthouse-core/test/fixtures/traces/perflog.json"
  },

  "aggregations": [{
    "name": "Performance Metrics",
    "description": "These encapsulate your app's performance.",
    "scored": false,
    "categorizable": false,
    "items": [{
      "audits": {
        "user-timings": { "expectedValue": 0, "weight": 1 },
        "critical-request-chains": { "expectedValue": 0, "weight": 1}
      }
    }]
  }]
}

Then, run with: lighthouse --config-path=config.json http://www.random.url

The traceviewer-based trace processor from node-big-rig was forked into Lighthouse. Additionally, the DevTools' Timeline Model is available as well. There may be advantages for using one model over another.

FAQ

What is the architecture?

See Lighthouse Architecture.

What is "Do Better Web"?

Do Better Web is an initiative within Lighthouse to help web developers modernize their existing web applications. By running a set of tests, developers can discover new web platform APIs, become aware of performance pitfalls, and learn (newer) best practices. In other words, do better on the web!

DBW is implemented as a set of standalone gatherers and audits that are run alongside the core Lighthouse tests. The tests show up under "Best Practices" in the report.

If you'd like to contribute, check the list of issues or propose a new audit by filing an issue.

Are results sent to a remote server?

Nope. Lighthouse runs locally, auditing a page using a local version of the Chrome browser installed the machine. Report results are never processed or beaconed to a remote server.

Lighthouse logo
Lighthouse, ˈlītˌhous (n): a tower or other structure tool containing a beacon light to warn or guide ships at sea developers.