### MySQL Setup for Testing Source: https://googlechrome.github.io/lighthouse-ci/CONTRIBUTING.md Commands to install, start, and configure MySQL for testing the server's MySQL support. Includes database creation, user grants, password setting, and environment variable export. ```bash brew install mysql brew services start mysql mysql -e "CREATE DATABASE IF NOT EXISTS lighthouse_ci_test;" -u root mysql -e "GRANT ALL ON lighthouse_ci_test.* TO 'lhci'@'localhost';" -u root mysql -e ALTER USER 'lhci'@'localhost' IDENTIFIED BY 'password';' -u root export MYSQL_DB_URL="mysql://lhci:password@localhost/lighthouse_ci_test" yarn test ``` -------------------------------- ### Lighthouse CI Server Configuration Examples Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Examples of advanced server configurations using command-line flags for storage and authentication. ```bash lhci server --storage.sqlDatabasePath=./lhci.db ``` ```bash lhci server --storage.sqlDialect=postgres --storage.sqlConnectionUrl="postgres://user@localhost/lighthouse_ci_db" ``` ```bash lhci server --storage.sqlDatabasePath=./lhci.db --basicAuth.username="customuser" --basicAuth.password="LighthouseRocks" ``` -------------------------------- ### Jenkins Setup for Lighthouse CI (Machine Setup) Source: https://googlechrome.github.io/lighthouse-ci/docs/getting-started.html Bash script to set up a Jenkins agent for Lighthouse CI on an Ubuntu-based system. It adds Google Chrome and Node.js repositories, then installs them. ```bash #!/bin/bash set -euxo pipefail # Add Chrome's apt-key echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" | sudo tee -a /etc/apt/sources.list.d/google.list wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | sudo apt-key add - # Add Node's apt-key curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - # Install NodeJS and Google Chrome sudo apt-get update sudo apt-get install -y nodejs google-chrome-stable ``` -------------------------------- ### Example package.json for Autorun Server Detection Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html This excerpt shows how to configure a `package.json` to allow `lhci autorun` to automatically detect and start your webserver using an npm script. ```json { "scripts": { "serve:lhci": "NODE_ENV=production npm run server" } } ``` -------------------------------- ### Install Yarn and Install Dependencies Source: https://googlechrome.github.io/lighthouse-ci/CONTRIBUTING.md Installs Yarn globally and then installs project dependencies using Yarn. Run this in the repository root. ```bash npm install -g yarn ``` ```bash yarn install # run in the repo root ``` -------------------------------- ### Lighthouse CI Upload CLI Examples Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Examples of using the `lhci upload` command with various configurations for uploading reports to Lighthouse CI. ```bash lhci upload --config=./lighthouserc.json ``` ```bash lhci upload --target=temporary-public-storage ``` ```bash lhci upload --serverBaseUrl=http://lhci.my-custom-domain.com/ ``` ```bash lhci upload --extraHeaders.Authorization='Bearer X92sEo3n1J1F0k1E9' ``` ```bash lhci upload --basicAuth.username="customuser" --basicAuth.password="LighthouseRocks" ``` ```bash lhci upload --githubToken="$MY_ENTERPRISE_GITHUB_TOKEN" --githubApiHost="https://custom-github-server.example.com/api/v3" ``` -------------------------------- ### Install and Run Lighthouse CI CLI Wizard Source: https://googlechrome.github.io/lighthouse-ci/docs/getting-started.html Install the Lighthouse CI CLI globally and use the wizard to create a new project, connecting it to your LHCI server. ```bash $ curl https://your-lhci-server.example.com/version # Make sure you can connect to your server. 0.x.x $ npm install -g @lhci/cli@0.15.x # Install the Lighthouse CI CLI. Installing... $ lhci wizard # Use the wizard to create a project. ? Which wizard do you want to run? new-project ? What is the URL of your LHCI server? https://your-lhci-server.example.com/ ? What would you like to name the project? My Favorite Project ? Where is the project's code hosted? https://github.com/GoogleChrome/lighthouse-ci Created project My Favorite Project (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)! Use build token XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX to connect. Use admin token XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX to manage the project. ``` -------------------------------- ### Lighthouse CI Collect Command Examples Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Demonstrates various ways to use the `lhci collect` command. This includes specifying the number of runs, starting a server, serving static files, auditing specific URLs, running on multiple URLs, and using Puppeteer for login. ```bash lhci collect --numberOfRuns=5 --url=https://example.com ``` ```bash lhci collect --start-server-command="yarn serve" --url=http://localhost:8080/ ``` ```bash lhci collect --staticDistDir=./dist ``` ```bash lhci collect --staticDistDir=./public --url=http://localhost/products/pricing/ ``` ```bash lhci collect --url=https://example-1.com --url=https://example-2.com ``` ```bash lhci collect --start-server-command="yarn serve" --url=http://localhost:8080/ --puppeteer-script=./path/to/login-with-puppeteer.js ``` -------------------------------- ### Autorun Command Example: Setting Upload Target Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Example of using the `autorun` command to specify the upload target. Note the required `=` syntax for atomic arguments. ```bash lhci autorun --upload.target=temporary-public-storage ``` -------------------------------- ### Example Puppeteer Script for Login Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html This script demonstrates how to use puppeteer to log in to a web page before Lighthouse CI runs. It navigates to the login page, enters credentials, and submits the form. Ensure 'puppeteer' is installed. ```javascript /** * @param {puppeteer.Browser} browser * @param context */ module.exports = async (browser, context) => { // launch browser for LHCI const page = await browser.newPage(); await page.goto('http://localhost:8080/login'); await page.type('#username', 'admin'); await page.type('#password', 'password'); await page.click('[type="submit"]'); await page.waitForNavigation(); // close session for next run await page.close(); }; ``` -------------------------------- ### Install LHCI Server and SQLite Source: https://googlechrome.github.io/lighthouse-ci/docs/server.html Installs the necessary packages for the LHCI server and SQLite database support. ```bash npm install @lhci/server sqlite3 ``` -------------------------------- ### Start LHCI Server with SQLite Source: https://googlechrome.github.io/lighthouse-ci/docs/server.html Programmatically starts the LHCI server using Node.js, configured to use SQLite for storage. ```javascript const {createServer} = require('@lhci/server'); console.log('Starting server...'); createServer({ port: process.env.PORT, storage: { storageMethod: 'sql', sqlDialect: 'sqlite', sqlDatabasePath: '/path/to/db.sql', }, }).then(({port}) => console.log('LHCI listening on port', port)); ``` -------------------------------- ### Run Server in Watch Mode and Start Server Source: https://googlechrome.github.io/lighthouse-ci/CONTRIBUTING.md Use these commands to build the server in watch mode and start the server process. The server process needs to be restarted if API changes are made. ```sh yarn build:watch yarn start:server ``` -------------------------------- ### Heroku Project Setup and Deployment Source: https://googlechrome.github.io/lighthouse-ci/docs/recipes/heroku-server Creates a new Heroku application, adds a PostgreSQL database add-on, scales the web dynos, and deploys the code to Heroku. ```bash heroku create heroku addons:create heroku-postgresql:essential-0 git push heroku main heroku ps:scale web=1 heroku open ``` -------------------------------- ### Install LHCI CLI and Server for Local Testing Source: https://googlechrome.github.io/lighthouse-ci/docs/server.html Installs the LHCI CLI and server packages as development dependencies for local testing. ```bash npm install -D @lhci/cli @lhci/server sqlite3 ``` -------------------------------- ### Start Lighthouse CI Server Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Initiate the Lighthouse CI server, typically run on dedicated infrastructure. Configure logging, port, storage method, and database options. ```bash Run Lighthouse CI server Options: --logLevel [string] [choices: "silent", "verbose"] [default: "verbose"] --port, -p [number] [default: 9001] --storage.storageMethod [string] [choices: "sql"] [default: "sql"] --storage.sqlDialect [string] [choices: "sqlite", "postgres", "mysql"] [default: "sqlite"] --storage.sqlDatabasePath The path to a SQLite database on disk. --storage.sqlConnectionUrl The connection url to a postgres or mysql database. --storage.sqlConnectionSsl Whether the SQL connection should force use of SSL [boolean] [default: false] --storage.sqlDangerouslyResetDatabase Whether to force the database to the required schema. WARNING: THIS WILL DELETE ALL DATA [boolean] [default: false] --storage.sqlMigrationOptions.tableName Use a different Sequelize table name. [string] --basicAuth.username The username to protect the server with HTTP Basic Authentication. [string] --basicAuth.password The password to protect the server with HTTP Basic Authentication. [string] ``` -------------------------------- ### Advanced YAML Configuration Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html An advanced configuration example using YAML for Lighthouse CI, covering collection, assertions, and upload settings. ```yaml ci: collect: numberOfRuns: 5 startServerCommand: rails server -e production url: - http://localhost:3000/ - http://localhost:3000/pricing - http://localhost:3000/support assert: preset: lighthouse:recommended assertions: offscreen-images: 'off' uses-webp-images: 'off' color-contrast: 'off' first-contentful-paint: - error - maxNumericValue: 2000 aggregationMethod: optimistic interactive: - error - maxNumericValue: 5000 aggregationMethod: optimistic upload: target: lhci serverBaseUrl: https://lhci.example.com ``` -------------------------------- ### Configure GitHub Actions for Lighthouse CI Source: https://googlechrome.github.io/lighthouse-ci/docs/getting-started.html This workflow configures GitHub Actions to check out code, set up Node.js, install dependencies, build the project, and run Lighthouse CI. It demonstrates how to install the LHCI CLI and use the `lhci autorun` command, setting the `LHCI_GITHUB_APP_TOKEN` environment variable for status checks. ```yaml name: CI on: [push] jobs: lhci: name: Lighthouse runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: ref: $ - name: Use Node.js 16.x uses: actions/setup-node@v3 with: node-version: 16.x - name: npm install, build run: | npm install npm run build - name: run Lighthouse CI run: | npm install -g @lhci/cli@0.15.x lhci autorun env: LHCI_GITHUB_APP_TOKEN: $ ``` -------------------------------- ### Configure GitLab CI for Lighthouse CI Source: https://googlechrome.github.io/lighthouse-ci/docs/getting-started.html Integrate Lighthouse CI into GitLab CI. This example uses a Docker image with Node.js and Chrome, installs dependencies, builds the project, and runs Lighthouse CI with specific upload targets and Chrome flags. ```js module.exports = { ci: { collect: { settings: { chromeFlags: '--no-sandbox', }, }, upload: { target: 'temporary-public-storage', }, }, }; ``` ```yaml image: cypress/browsers:node16.17.0-chrome106 lhci: script: - npm install - npm run build - npm install -g @lhci/cli@0.15.x - lhci autorun --upload.target=temporary-public-storage --collect.settings.chromeFlags="--no-sandbox" || echo "LHCI failed!" ``` -------------------------------- ### Example: Running Healthcheck with Fatal Error and Specific Checks Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Demonstrates how to run the `healthcheck` command, enabling fatal error exit and specifying checks for GitHub token. ```bash lhci healthcheck --fatal --checks=githubToken ``` -------------------------------- ### Configure Non-NodeJS Development Server Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Specify a command to start a development server and define URLs to collect for non-NodeJS projects. ```json { "ci": { "collect": { "startServerCommand": "rails server -e production", "url": [ "http://localhost:3000/", "http://localhost:3000/pricing", "http://localhost:3000/support" ] } } } ``` -------------------------------- ### Run LHCI Server Locally via CLI with SQLite Source: https://googlechrome.github.io/lighthouse-ci/docs/server.html Starts the LHCI server using the CLI, configured for local SQLite database storage. ```bash npx lhci server --storage.storageMethod=sql --storage.sqlDialect=sqlite --storage.sqlDatabasePath=./db.sql ``` -------------------------------- ### Run LHCI Server Locally with Docker Source: https://googlechrome.github.io/lighthouse-ci/docs/server.html Starts the LHCI server in a Docker container, mounting a volume for data persistence. ```bash docker volume create lhci-data docker container run --publish 9001:9001 --mount='source=lhci-data,target=/data' --detach patrickhulce/lhci-server ``` -------------------------------- ### Configure GitHub Actions for Lighthouse CI Source: https://googlechrome.github.io/lighthouse-ci/docs/getting-started.html Set up GitHub Actions to automatically run Lighthouse CI on push events. This includes checking out code, setting up Node.js, installing dependencies, building the project, and running Lighthouse CI. ```yaml name: CI on: [push] jobs: lhci: name: Lighthouse runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Use Node.js 16.x uses: actions/setup-node@v3 with: node-version: 16.x - name: npm install, build run: | npm install npm run build - name: run Lighthouse CI run: | npm install -g @lhci/cli@0.15.x lhci autorun ``` -------------------------------- ### Configure Circle CI for Lighthouse CI Source: https://googlechrome.github.io/lighthouse-ci/docs/getting-started.html Set up Lighthouse CI within Circle CI using a Node.js Docker image with Chrome. This involves checking out code, installing Chrome, installing dependencies, building the project, and running Lighthouse CI. ```yaml version: 2.1 orbs: browser-tools: circleci/browser-tools@1.2.3 jobs: build: docker: - image: cimg/node:16.13-browsers working_directory: ~/your-project steps: - checkout - browser-tools/install-chrome - run: npm install - run: npm run build - run: sudo npm install -g @lhci/cli@0.15.x - run: lhci autorun ``` -------------------------------- ### Lighthouse CI Complete Experience Configuration Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html A comprehensive configuration for advanced users, including increased runs, performance budgets, and server setup for tracking scores and regressions. ```json { "ci": { "collect": { "numberOfRuns": 5 }, "assert": { "preset": "lighthouse:recommended", "assertions": { "first-contentful-paint": [ "error", {"maxNumericValue": 2000, "aggregationMethod": "optimistic"} ], "interactive": ["error", {"maxNumericValue": 5000, "aggregationMethod": "optimistic"}] // ... } }, "upload": { "target": "lhci", "serverBaseUrl": "https://lhci.example.com" } } } ``` -------------------------------- ### Configure Custom Server and URL in lighthouserc.js Source: https://googlechrome.github.io/lighthouse-ci/docs/getting-started.html Use this configuration when your site requires a custom server. It specifies the command to start your server and the URLs to audit. ```javascript module.exports = { ci: { collect: { url: ['http://localhost:3000/'], startServerCommand: 'rails server -e production', }, upload: { target: 'temporary-public-storage', }, }, }; ``` -------------------------------- ### Integrate LHCI Server with Fastify Middleware Source: https://googlechrome.github.io/lighthouse-ci/docs/server.html This example demonstrates how to use the LHCI server with Fastify, including necessary configurations for body parsing and request handling. ```javascript const fastify = require('fastify'); const lhci = require('@lhci/server'); (async () => { const {app} = await createApp({ // you need that for use fastify useBodyParser: false, storage: { storageMethod: 'sql', sqlDialect: 'sqlite', // see configuration... }, }); const fastify = require('fastify')({ logger: true }) fastify.all( '/*', async (req, reply) => { // you need to clone the body for express or this will be emit error req.raw.body = req.body; await app(req.raw, reply.raw); // don't forget that or fastify will be not respond reply.hijack(); } ); // Run the server! fastify.listen({ port: 3000 }, function (err, address) { if (err) { fastify.log.error(err) process.exit(1) } // Server is now listening on ${address} }) })(); ``` -------------------------------- ### Configure Travis CI for Lighthouse CI Source: https://googlechrome.github.io/lighthouse-ci/docs/getting-started.html Integrate Lighthouse CI into Travis CI. This configuration specifies the Node.js version, installs Chrome, installs the Lighthouse CI CLI, builds the project, and runs Lighthouse CI. ```yaml language: node_js node_js: - v16 addons: chrome: stable before_install: - npm install -g @lhci/cli@0.15.x script: - npm run build - lhci autorun ``` -------------------------------- ### Configure GCP and Deploy LHCI Server to Kubernetes Source: https://googlechrome.github.io/lighthouse-ci/docs/recipes/docker-server Sets up Google Cloud configuration, creates a Kubernetes cluster, and deploys the LHCI server using provided YAML configuration files. Ensure you have the Google Cloud SDK installed. ```bash # Configure the gcloud utility PROJECT_ID="" COMPUTE_ZONE="" gcloud config set project "$PROJECT_ID" gcloud config set compute/zone "$COMPUTE_ZONE" # Create our Kubernetes cluster for LHCI gcloud container clusters create lhci-cluster --num-nodes=1 # Deploy the LHCI server curl -O https://raw.githubusercontent.com/GoogleChrome/lighthouse-ci/main/docs/recipes/docker-server/kubernetes/lhci-data-claim.yml curl -O https://raw.githubusercontent.com/GoogleChrome/lighthouse-ci/main/docs/recipes/docker-server/kubernetes/lhci-deployment.yml curl -O https://raw.githubusercontent.com/GoogleChrome/lighthouse-ci/main/docs/recipes/docker-server/kubernetes/lhci-service.yml kubectl apply -f ./lhci-data-claim.yml kubectl apply -f ./lhci-deployment.yml kubectl apply -f ./lhci-service.yml # Make sure our deployment was created successfully kubectl get deployment # Check the IP of your LHCI server installation! kubectl get service # lhci-server's EXTERNAL-IP is your `LHCI_SERVER_BASE_URL` # NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE # kubernetes ClusterIP 10.X.X.X 443/TCP 9m # lhci-server LoadBalancer 10.X.X.X X.X.X.X 80:XXXXX/TCP 2m ``` -------------------------------- ### Configure Assertions with CLI Flags Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Customize assertion rules using CLI flags. This example sets the preset to 'lighthouse:recommended' and disables the 'uses-webp-images' assertion. ```bash lhci assert --preset=lighthouse:recommended --assertions.uses-webp-images=off ``` -------------------------------- ### Autorun Command Example: Setting Collect Runs Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Example of using the `autorun` command to specify the number of runs for the `collect` phase. Note the required `=` syntax for atomic arguments. ```bash lhci autorun --collect.numberOfRuns=5 ``` -------------------------------- ### Static Directory File Discovery Depth Example Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Illustrates the directory structure and depth for `staticDirFileDiscoveryDepth`. Lighthouse will recursively search for URLs up to the specified depth, with a default of 2. ```treeview public/ ├── index.html #level 0 ├── contact/ │ └── index.html #level 1 ├── projects/ │ ├──index.html #level 1 │ └── crisis/ │ ├──index.html #level 2 │ └── earthquake/ │ └── index.html #level 3 ``` -------------------------------- ### Jenkins Job Configuration for Lighthouse CI Source: https://googlechrome.github.io/lighthouse-ci/docs/getting-started.html Bash script for a Jenkins job to run Lighthouse CI. It installs dependencies, builds the project, sets Chrome path and build URL environment variables, installs the Lighthouse CI CLI, and runs the autorun command. ```bash #!/bin/bash set -euxo pipefail npm install npm run build export CHROME_PATH=$(which google-chrome-stable) export LHCI_BUILD_CONTEXT__EXTERNAL_BUILD_URL="$BUILD_URL" npm install -g @lhci/cli@0.15.x lhci autorun ``` -------------------------------- ### Integrate Custom Express Middleware with LHCI Server Source: https://googlechrome.github.io/lighthouse-ci/docs/server.html This example shows how to create an Express app and integrate the LHCI server's app as middleware. Custom authentication can be added before the LHCI app. ```javascript const express = require('express'); const lhci = require('@lhci/server'); (async () => { const app = express(); const {app: lhciApp} = await lhci.createApp({ storage: { storageMethod: 'sql', sqlDialect: 'sqlite', // see configuration... }, }); app.use((req, res, next) => handleCustomAuthentication(req, res, next)); app.use(lhciApp); app.listen(); })(); ``` -------------------------------- ### GitHub Actions CI Workflow for Lighthouse CI Source: https://googlechrome.github.io/lighthouse-ci This YAML configuration sets up a GitHub Actions workflow to automatically run Lighthouse CI on every push event. It checks out the code, sets up Node.js, installs dependencies including the Lighthouse CI CLI, builds the project, and then runs the Lighthouse CI autorun command. ```yaml name: CI on: [push] jobs: lighthouseci: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 18 - run: npm install && npm install -g @lhci/cli@0.15.x - run: npm run build - run: lhci autorun ``` -------------------------------- ### Run Published LHCI Server Image Source: https://googlechrome.github.io/lighthouse-ci/docs/recipes/docker-server Creates a persistent data volume and runs the pre-published LHCI server Docker image from Docker Hub. This is a quicker way to start the server without building locally. ```bash docker volume create lhci-data docker container run --publish 9001:9001 --mount='source=lhci-data,target=/data' --detach patrickhulce/lhci-server ``` -------------------------------- ### Get Project Slugs with cURL Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Use cURL to list projects and their slugs from the Lighthouse CI server API. This is useful for identifying the `projectSlug` needed for PSI collection configuration. ```bash curl http://localhost:9001/v1/projects | jq '.[] |.name,.slug' ``` -------------------------------- ### Enable Desktop Emulation Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Configure Lighthouse CI to emulate a desktop device during collection. ```json { "ci": { "collect": { "settings": { "preset": "desktop" } } } } ``` -------------------------------- ### Initialize LHCI Heroku Project Source: https://googlechrome.github.io/lighthouse-ci/docs/recipes/heroku-server Sets up a new directory, initializes a Git repository, and downloads the necessary package.json and server.js files for the Heroku deployment. ```bash mkdir lhci-heroku && cd lhci-heroku && git init curl https://raw.githubusercontent.com/GoogleChrome/lighthouse-ci/main/docs/recipes/heroku-server/package.json > package.json curl https://raw.githubusercontent.com/GoogleChrome/lighthouse-ci/main/docs/recipes/heroku-server/server.js > server.js git add package.json server.js && git commit -m 'Initial commit' ``` -------------------------------- ### Run Lighthouse CI Wizard Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Launch an interactive wizard to perform various Lighthouse CI tasks, such as setting up new projects or managing server tokens. ```bash lhci wizard ? Which wizard do you want to run? (Use arrow keys) ❯ new-project reset-build-token reset-admin-token ``` -------------------------------- ### Lighthouse CI Configuration in YAML Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Set up Lighthouse CI using a `lighthouserc.yml` file. This format allows for a more concise representation of configuration options, grouped by command. ```yaml ci: collect: # collect options here assert: # assert options here upload: # upload options here server: # server options here wizard: # wizard options here ``` -------------------------------- ### Configure Basic Auth for Server Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Enable basic authentication for the Lighthouse CI server. ```json { "ci": { "server": { "basicAuth": { "username": "myusername", "password": "LighthouseRocks" }, "storage": { // ... } } } } ``` -------------------------------- ### Update LHCI Server on Heroku Source: https://googlechrome.github.io/lighthouse-ci/docs/recipes/heroku-server Updates the Lighthouse CI server to the latest version by installing the package, committing the changes, and pushing them to Heroku. ```bash npm install --save @lhci/server@latest git add package.json && git commit -m 'update LHCI' git push heroku main ``` -------------------------------- ### Configure Google Cloud Build for Lighthouse CI Source: https://googlechrome.github.io/lighthouse-ci/docs/getting-started.html Set up Google Cloud Build to run Lighthouse CI. This includes a configuration file for Lighthouse CI and the Cloud Build YAML definition. ```js module.exports = { ci: { collect: { settings: { chromeFlags: '--no-sandbox', }, }, upload: { target: 'temporary-public-storage', }, }, }; ``` ```yaml steps: - id: 'install' args: ['npm', 'ci'] name: node:16-alpine - id: 'build' waitFor: ['install'] name: node:16-alpine args: ['npm', 'run', 'build'] - id: 'lighthouse' waitFor: ['build'] name: cypress/browsers:node16.17.0-chrome106 entrypoint: '/bin/sh' args: ['-c', 'npm install -g @lhci/cli@0.15.x && lhci autorun --failOnUploadFailure'] env: - 'LHCI_BUILD_CONTEXT__CURRENT_BRANCH=$BRANCH_NAME' options: machineType: 'N1_HIGHCPU_8' ``` -------------------------------- ### Troubleshooting GCP Kubernetes Connection Source: https://googlechrome.github.io/lighthouse-ci/docs/recipes/docker-server Command to re-establish connection to the 'lhci-server' cluster if you encounter permissions issues or are not connected to the correct cluster after initial setup. ```bash gcloud container clusters get-credentials lhci-server --zone $COMPUTE_ZONE --project $PROJECT_ID ``` -------------------------------- ### Configure Budgets.json Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Set a path to a budgets.json file to include performance budgets in the Lighthouse report and assert their passing. ```json { "ci": { "collect": { "settings": { "budgetPath": "./path/to/budgets.json" } }, "assert": { "assertions": { "performance-budget": "error" } } } } ``` -------------------------------- ### Unit Tests Source: https://googlechrome.github.io/lighthouse-ci/CONTRIBUTING.md Run unit tests for the project. ```bash yarn test:unit ``` -------------------------------- ### Lighthouse CI Upload Options Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html This snippet lists the available command-line options for the `lhci upload` command. These options control where reports are saved, authentication, and status checks. ```bash Options: --target The type of target to upload the data to. If set to anything other than "lhci", some of the options will not apply. [string] [choices: "lhci", "temporary-public-storage", "filesystem"] [default: "lhci"] --token [lhci only] The Lighthouse CI build token for the project.[string] --ignoreDuplicateBuildFailure [lhci only] Whether to ignore failures (still exit with code 0) caused by uploads of a duplicate build. [boolean] --githubToken The GitHub token to use to apply a status check. [string] --githubApiHost The GitHub host to use for the status check API request. Modify this when using on a GitHub Enterprise server. [string] [default: "https://api.github.com"] --githubAppToken The LHCI GitHub App token to use to apply a status check. [string] --githubStatusContextSuffix The suffix of the GitHub status check context label. [string] --extraHeaders [lhci only] Extra headers to use when making API requests to the LHCI server. --basicAuth.username [lhci only] The username to use on a server protected with HTTP Basic Authentication. [string] --basicAuth.password [lhci only] The password to use on a server protected with HTTP Basic Authentication. [string] --serverBaseUrl [lhci only] The base URL of the LHCI server where results will be saved. [default: "http://localhost:9001/"] --uploadUrlMap [temporary-public-storage only] Whether to post links to historical base results to storage or not. Defaults to true only on master branch. [boolean] [default: false] --urlReplacementPatterns [lhci only] sed-like replacement patterns to mask non-deterministic URL substrings. [array] [default: ["s#:[0-9]{3,5}/#:PORT/#","s/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/UUID/ig" ]] --outputDir [filesystem only] The directory in which to dump Lighthouse results. [string] --reportFilenamePattern [filesystem only] The pattern to use for naming Lighthouse reports. [string] [default: "%%HOSTNAME%%-%%PATHNAME%%-%%DATETIME%%.report.%%EXTENSION%%"] ``` -------------------------------- ### Configure Basic Auth for Upload Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Set up basic authentication credentials for uploading Lighthouse CI results. ```json { "ci": { "upload": { "basicAuth": { "username": "myusername", "password": "LighthouseRocks" } } } } ``` -------------------------------- ### Configure Lighthouse CI Project Settings Source: https://googlechrome.github.io/lighthouse-ci/docs/getting-started.html Configure your Lighthouse CI project by specifying the server URL and build token in the lighthouserc.js file. The token can also be set using the LHCI_TOKEN environment variable. ```javascript module.exports = { ci: { upload: { target: 'lhci', serverBaseUrl: 'https://your-lhci-server-url.example.com', token: 'Your *build token* goes here', // could also use LHCI_TOKEN variable instead }, }, }; ``` -------------------------------- ### Configure Lighthouse CI Assertions with Preset Source: https://googlechrome.github.io/lighthouse-ci/docs/getting-started.html Use the `assert.preset` option in your `lighthouserc.js` file to automatically apply a predefined set of Lighthouse audit assertions. This is a good starting point for performance goals. ```javascript module.exports = { ci: { // ... assert: { preset: 'lighthouse:recommended', }, // ... }, }; ``` -------------------------------- ### Lighthouse CI Easy Mode Configuration Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html A basic configuration for new users, focusing on uploading results to temporary public storage. ```json { "ci": { "upload": { "target": "temporary-public-storage" } } } ``` -------------------------------- ### Configure Git Depth in Travis CI Source: https://googlechrome.github.io/lighthouse-ci/docs/troubleshooting.html Set the git depth in your .travis.yml to a value sufficient for detecting base branches. A depth of 20 is shown as an example. Disabling depth entirely is also an option. ```yaml git: #### Example: clone with the past 20 commits ###### depth: 20 #### Example: disable git depth entirely ###### depth: false ``` -------------------------------- ### Configure Assertions with Presets and Custom Audits Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Use presets like `lighthouse:no-pwa` and customize specific audits. Adjust thresholds for numeric values and disable audits as needed. ```json { "ci": { "assert": { "preset": "lighthouse:no-pwa", "assertions": { "dom-size": ["error", {"maxNumericValue": 3000}], "offscreen-images": "off", "color-contrast": "off", "tap-targets": "off" } } } } ``` -------------------------------- ### Build and Run LHCI Server Locally Source: https://googlechrome.github.io/lighthouse-ci/docs/recipes/docker-server Builds the LHCI Docker image, creates a persistent data volume, and runs the server in detached mode. Access the server via http://localhost:9001/app/. ```bash docker image build -t lhci . docker volume create lhci-data docker container run --publish 9001:9001 --mount='source=lhci-data,target=/data' --detach lhci open http://localhost:9001/app/ ``` -------------------------------- ### Global Options for Lighthouse CI Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html These are general options applicable to most Lighthouse CI commands. They control help output, version display, and configuration file usage. ```bash --help Show help [boolean] --version Show version number [boolean] --no-lighthouserc Disables automatic usage of a .lighthouserc file. [boolean] --config Path to JSON config file. ``` -------------------------------- ### Open Local Lighthouse Report Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Serve a local Lighthouse report generated by the `collect` command. No specific configuration is required for this command. ```bash lhci open ``` -------------------------------- ### Configure Assertions with Custom Budget Limits Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Consolidate budget assertions directly within the main configuration. Note that file size units differ between `budgets.json` (kilobytes) and Lighthouse CI assertions (bytes). ```json { "ci": { "assert": { "assertions": { "first-contentful-paint": ["warn", {"maxNumericValue": 4000}], "viewport": "error", "resource-summary:document:size": ["error", {"maxNumericValue": 14000}], "resource-summary:font:count": ["warn", {"maxNumericValue": 1}], "resource-summary:third-party:count": ["warn", {"maxNumericValue": 5}] } } } } ``` -------------------------------- ### Basic Lighthouse CI Configuration Source: https://googlechrome.github.io/lighthouse-ci/docs/getting-started.html This configuration enables Lighthouse CI to upload reports to temporary public storage. Place this file at the root of your repository. ```javascript module.exports = { ci: { upload: { target: 'temporary-public-storage', }, }, }; ``` -------------------------------- ### Configure Output Directory for Reports Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Specify the directory relative to the current working directory where `manifest.json` and Lighthouse reports will be output. Existing `manifest.json` files will be overwritten. ```json { "ci": { "outputDir": "./lhci" } } ``` -------------------------------- ### Configure Basic Authentication for LHCI Server Source: https://googlechrome.github.io/lighthouse-ci/docs/server.html Use these flags to set up HTTP Basic authentication for the LHCI server. Ensure the same credentials are used in your upload steps. ```bash lhci server --basicAuth.username=myusername --basicAuth.password=mypassword ``` ```bash lhci autorun --upload.basicAuth.username=myusername --upload.basicAuth.password=mypassword ``` -------------------------------- ### Run All Tests Source: https://googlechrome.github.io/lighthouse-ci/CONTRIBUTING.md Execute all defined tests including typechecking, linting, and unit tests. ```bash yarn test ``` -------------------------------- ### Troubleshoot and Reinstall Dependencies Source: https://googlechrome.github.io/lighthouse-ci/CONTRIBUTING.md If you encounter problems, remove the node_modules directory, reinstall dependencies, and rebuild the project. ```sh trash node_modules && yarn install yarn build ``` -------------------------------- ### Apply Docker Security Options for Chrome Sandboxing Source: https://googlechrome.github.io/lighthouse-ci/docs/recipes/docker-client Use this command to run a Docker container with a tailored seccomp profile that grants Chrome the necessary syscall permissions. ```bash docker run --security-opt seccomp:./seccomp-chrome.json ``` -------------------------------- ### Build, Tag, and Push Custom LHCI Docker Image Source: https://googlechrome.github.io/lighthouse-ci/docs/recipes/docker-server Builds a local LHCI Docker image, tags it for Docker Hub, and pushes it to your own repository. Use this if you've made modifications to the LHCI server code. ```bash docker image build -t lhci . docker tag lhci:latest /lhci-server:latest docker push /lhci-server:latest ``` -------------------------------- ### Run Lighthouse CI Assertions Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Execute Lighthouse CI assertions using a configuration file or specific command-line flags. Control the output by including or excluding passed assertions. ```bash lhci assert --config=./lighthouserc.json ``` ```bash lhci assert --budgetsFile=./budgets.json ``` ```bash lhci assert --preset=lighthouse:recommended --assertions.speed-index=off ``` ```bash lhci assert --preset=lighthouse:recommended --includePassedAssertions ``` -------------------------------- ### Configure Custom SSL Certificate for Database Connection Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Set up custom SSL certificates for a secure PostgreSQL database connection. ```javascript const fs = require('fs'); module.exports = { ci: { server: { storage: { storageMethod: 'sql', sqlDialect: 'postgres', sqlConnectionSsl: true, sqlConnectionUrl: process.env.DATABASE_URL, sqlDialectOptions: { ssl: { ca: fs.readFileSync('./certs/ca.crt', 'utf8'), key: fs.readFileSync('./certs/client.foo.key', 'utf8'), cert: fs.readFileSync('./certs/client.foo.crt', 'utf8'), } }, }, }, }, }; ``` -------------------------------- ### Build and Push Custom LHCI Docker Image Source: https://googlechrome.github.io/lighthouse-ci/docs/recipes/docker-client Build a local Docker image for the LHCI client and push it to Docker Hub. Replace \"\" with your actual Docker Hub username. ```bash docker image build -t lhci-client . docker tag lhci-client:latest /lhci-client:latest docker push /lhci-client:latest ``` -------------------------------- ### Lighthouse CI Configuration in JSON Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Configure Lighthouse CI settings using a `lighthouserc.json` file. The structure mirrors the JavaScript configuration, with options organized by command. ```json { "ci": { "collect": { // collect options here }, "assert": { // assert options here }, "upload": { // upload options here }, "server": { // server options here }, "wizard": { // wizard options here } } } ``` -------------------------------- ### Configure Lighthouse Settings Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Customize Lighthouse behavior by providing a path to a custom config file, specifying plugins, or disabling storage reset. ```json { "ci": { "collect": { "settings": { "configPath": "./path/to/lighthouse/config.js", "plugins": ["lighthouse-plugin-field-performance"], "disableStorageReset": true } } } } ``` -------------------------------- ### Lighthouse CI Next Level Configuration Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html An intermediate configuration that asserts a recommended preset but allows disabling specific failing audits. ```json { "ci": { "assert": { "preset": "lighthouse:recommended", "assertions": { "offscreen-images": "off", "uses-webp-images": "off", "color-contrast": "off" // ... } }, "upload": { "target": "temporary-public-storage" } } } ``` -------------------------------- ### Lighthouse CI Configuration in JavaScript Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Define Lighthouse CI configuration options within a `lighthouserc.js` file. Options are grouped by command (collect, assert, upload, server, wizard). ```javascript module.exports = { ci: { collect: { // collect options here }, assert: { // assert options here }, upload: { // upload options here }, server: { // server options here }, wizard: { // wizard options here }, }, }; ``` -------------------------------- ### Lighthouse CI Assert CLI Options Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Command-line options for the `lhci assert` command, used to verify Lighthouse CI conditions and exit with appropriate status codes. ```bash Options: --preset The assertions preset to extend [choices: "lighthouse:all", "lighthouse:recommended", "lighthouse:no-pwa"] --assertions The assertions to use. --budgetsFile The path (relative to cwd) to a budgets.json file. --includePassedAssertions Whether to include the results of passed assertions in the output. [boolean] ``` -------------------------------- ### Configure Custom Sequelize Options Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Customize Sequelize options, such as connection pool settings, for SQL storage. ```javascript module.exports = { ci: { server: { storage: { storageMethod: 'sql', sqlDialect: 'postgres', sqlConnectionSsl: true, sqlConnectionUrl: process.env.DATABASE_URL, sqlDialectOptions: { // this flag also needs to be set in order to make a secure connection if not setting custom certificates ssl: true, }, sequelizeOptions: { pool: { acquire: 30000, }, }, }, }, }, }; ``` -------------------------------- ### Configure Assertions with a Budgets File Source: https://googlechrome.github.io/lighthouse-ci/docs/configuration.html Specify a `budgetsFile` to configure assertions using a separate JSON file. This option cannot be used with other assertion configuration methods. ```json { "ci": { "assert": { "budgetsFile": "path/from/cwd/to/budget.json" } } } ```