How to add Lighthouse to a continuous integration system, like GitHub Actions.
Fast loading times
CI headlight is a set of tools to use Lighthouse during continuous integration. Lighthouse CI can be incorporated into developer workflows in many different ways. This guide covers the following topics:
- Using the Lighthouse CI CLI.
- Configuring your CI provider to run Lighthouse CI.
- Set up a GitHub action and
status check
for Lighthouse CI. This will automatically show Lighthouse results in GitHub pull requests. - Create a performance dashboard and data warehouse for Lighthouse reports.
Overview
Lighthouse CI es un conjunto de herramientas gratuitas que facilitan el uso de Lighthouse para la supervisión del rendimiento. Un solo informe Lighthouse proporciona una instantánea del rendimiento de una página web en el momento en que se ejecuta; Lighthouse CI muestra cómo estos hallazgos han cambiado con el tiempo. Esto se puede usar para identificar el impacto de cambios de código particulares o garantizar que se cumplan los umbrales de rendimiento durante los procesos de integración continua. Aunque la supervisión del rendimiento es el caso de uso más común de Lighthouse CI, se puede utilizar para supervisar otros aspectos del informe Lighthouse, por ejemplo, SEO ¿Qué es SEO o search engine optimization? Conjunto de prácticas destinadas a mejorar el posicionamiento de una web en el ranking de resultados de los motores de búsqueda. Al contrario que la estrategia SEM, que contempla la inclusión de enlaces contratados para obtener este objetivo, el procedimiento SEO se ocupa exclusivamente de los resultados naturales (no pagados) localizados por el algoritmo propio de cada buscador. Para esto contempla ajustar plus or accessibilityAccesibilidad significa que algo puede ser usado, obtenido, acercado, ingresado o alcanzado. De ello pueden derivarse dos significados aplicables a Internet. En primer lugar, la provisión de acceso a Internet a las personas con discapacidad o a las personas mayores lo más libre viable de barreras y, en segundo lugar, la accesibilidad y la legibilidad de una web para un crawler. Accesibilidad en términos de ausencia de barreras Actualmente, Internet plus.
The primary functionality of Lighthouse CI is provided by the Lighthouse CI command line interface. (Note: this is a separate tool from the Lighthouse CLI.) The Lighthouse CI CLI provides a set of
commands
to use Lighthouse CI. For example, him autorun The command runs multiple Lighthouse runs, identifies the Medium Lighthouse report, and loads the report for storage. This behavior can be highly customized by passing additional flags or by customizing the Lighthouse CI configuration file, lighthouserc.js.
Although the core functionality of Lighthouse CI is primarily encapsulated in the Lighthouse CI CLI, Lighthouse CI is typically used through one of the following approaches:
- Running Lighthouse CI as part of continuous integration
- Using a Lighthouse CI GitHub action that runs and comments on every pull request
- Track performance over time through the dashboard provided by Lighthouse Server.
All of these approaches are based on the Lighthouse CI CLI.
Las alternativas a Lighthouse CI incluyen servicios de monitoreo de rendimiento de terceros o escribir su propio script para recopilar datos de rendimiento durante el proceso de CI. Debería considerar el uso de un servicio de terceros si prefiere dejar que otra persona se encargue de la administración de su serverLos servidores son ordenadores centrales y potentes dentro del campo de la tecnología de la información que procesan y proporcionan software y archivos en una red. Desde el punto de vista de un cliente, varios ordenadores en una red pueden ponerse en contacto con el servidor central para conseguir la información solicitada. En la arquitectura cliente-servidor, el servidor puede ser un software que proporciona un servicio y se ejecuta en plus de monitoreo de rendimiento y dispositivos de prueba, o si desea capacidades de notificación (como correo electrónico o integración de SlackConcepto de Slack¿Qué es Slack?Slack es una herramienta, un programa que facilita la colaboración entre todo un equipo para llevar adelante prácticamente cualquier tarea. Se utiliza mucho en el entorno del marketing y además dentro de las empresas, puesto que es una aplicación que puede instalarse tanto en ordenador como en smartphones para conectar con facilidad a los empleados.Un entorno que permite reunir información, la comunicación entre usuarios conectados en plus) sin tener que crearlas. características usted mismo.
Use Lighthouse CI locally
This section explains how to run and install the Lighthouse CI CLI locally and how to configure lighthouserc.js. Running the Lighthouse CI CLI locally is the easiest way to ensure that your lighthouserc.js is configured correctly.
-
Install the Lighthouse CI CLI.
npm install -g @lhci/cliLighthouse CI is configured by placing a
lighthouserc.jsfile in the root of your project repository. This file is required and will contain configuration information related to Lighthouse CI. Although Lighthouse CI can configured to be used without a git repository, the instructions in this article assume that your project repository is configured to use git. -
In the root of your repository, create a
lighthouserc.jsconfiguration file.touch lighthouserc.js -
Add the following code to
lighthouserc.js. This code is an empty Lighthouse CI configuration. You will add to this configuration in later steps.module.exports = {
ci: {
collect: {
},
upload: {
},
},
}; -
Every time Lighthouse CI runs, it starts a server to serve your site. This server is what allows Lighthouse to load your site even when there are no other servers running. When Lighthouse CI finishes running, it will automatically shut down the server. To make sure the publication works correctly, you must configure the
staticDistDirproperties.
If your site is static, add the
staticDistDirproperty toci.collect
object to indicate where your static files are located. Lighthouse CI will use its own server to serve these files while you test your site. If your site is not static, add thestartServerCommandproperty to
ci.collectobject to indicate the command that starts your server. Lighthouse CI will start a new server process during the test and shut it down afterwards.
collect: {
staticDistDir: './public',
}
collect: {
startServerCommand: 'npm run start',
} -
Add the
urlEl URL (Localizador Uniforme de Recursos), es una dirección definida que apunta a la posición de un archivo en un servidor y lo recupera. Las URL se introducen en un navegador web para ingresar a documentos en la web o se incrustan como hipervínculos dentro de un documento. Se puede usar un Permalink para que una URL esté disponible de forma permanente. Componentes de una URL • prefijo de protocolo plusproperty to
ci.collectobject to indicate URL (s) where Lighthouse CI should run Lighthouse. The value of theurlthe property must be provided as a URL array; this array can contain one or more URLs. By default, Lighthouse CI will run Lighthouse three times on each URL.collect: {
url: ['httpEl HTTP (Hyper Text Transfer Protocol) es un protocolo que se usa para transmitir datos en redes. HTTP es un estándar técnico generalmente aceptado que establece cómo un cliente web se comunica con un servidor para que los datos solicitados por el cliente puedan ser cargados y mostrados. Información general Junto con el URL y el HTML, HTTP es uno de los conceptos más importantes de Internet (www). Fue desarrollado plus://localhost:8080']
}Note: The server you configured in the previous step should be able to publish these URLs. So if you are running Lighthouse CI locally these URLs should probably include
localhostinstead of your production host. -
Add the
targetConcepto de Target¿Qué es el Target?El Target es uno de los conceptos primordiales del marketing. Se usa para hablar del público al que se destinan las acciones y estrategias de cualquier campaña publicitaria o comercial. Es el objetivo al que ha de hablarle marca para suministrarle sus servicios o productos, aquellos a los que les interesa lo que brindan o pueda resultarle interesante por afinidad o por necesidades.Es uno de plusproperty to
ci.uploadobject and set the value to
'temporary-public-storage'. The Lighthouse reports collected by Lighthouese CI will be uploaded to temporary public storage. The report will stay there for seven days and then it will be automatically deleted. This configuration guide uses the "temporary public storage" upload option because it is quick to configure. For information on other ways to store Lighthouse reports, see the
documentation.upload: {
target: 'temporary-public-storage',
}The report storage location will look like this:
httpsHTTPS (protocolo de Transferencia de Hiper-Texto) es un protocolo que permite determinar una conexión segura entre el servidor y el cliente, que no puede ser interceptada por personas no autorizadas. En resumidas cuentas, es la versión segura de el http (Hyper Text Transfer Protocol) Cómo funciona Una conexión HTTP estándar en Internet puede ser fácilmente secuestrada por partes no autorizadas. El propósito de una conexión HTTPS es evitar esto: encriptar plus://storage.googleapis.com/lighthouse-infrastructure.appspot.com/reports/1580152437799-46441.report.html(This URL will not work because the report has already been removed.)
-
Run the Lighthouse CI CLI from the terminal using the
autoruncommand. This will run Lighthouse three times and load the Medium Lighthouse report.lhci autorunIf you have successfully configured Lighthouse CI, running this command should produce output similar to this:
✅ .lighthouseci/ directory writable
✅ Configuration file found
✅ Chrome installation found
⚠️ GitHub token not set
Healthcheck passed!Started a web server on port 65324...
Running Lighthouse 3 time(s) on http://localhost:65324/index.html
Run
Run
Run
Done running Lighthouse!Uploading median LHR of http://localhost:65324/index.html...success!
Open the report at https://storage.googleapis.com/lighthouse-infrastructure.appspot.com/reports/1591720514021-82403.report.html
No GitHub token set, skipping GitHub status check.Done running autorun.
You can ignore the
GitHub token not setmessage in the console output. A GitHub token is only required if you want to use Lighthouse CI with a GitHub action. How to configure a GitHub action is explained later in this article.By clicking on the linkConcepto de Dominio¿Qué es un Enlace?En Internet, un link, además conocido como enlace o hipervínculo, es cualquier texto o imagen que se encuentra en una página web y en la que el usuario puede pulsar o clicar para ser dirigido a otro contenido distinto. Es el principal medio de “desplazamiento” en la red, puesto que se encuentra presente en prácticamente cualquier portal que visites a día de hoy, inclusive en plus en la salida que comienza con
https: //storage.googleapis.com ...will take you to the Lighthouse report for Lighthouse's medium run.The default values used by
autoruncan be overridden via command line or
lighthouserc.js. For example, himlighthouserc.jsThe following configuration indicates that five Lighthouse executions should be collected at a timeautorun
run. -
To update
lighthouserc.jsuse thenumberOfRunsproperty:module.exports = {
collect: {
numberOfRuns: 5
},
},
}; -
Run the
autoruncommand:lhci autorunThe terminal output should show that Lighthouse has been run five times instead of the default three:
✅ .lighthouseci/ directory writable
✅ Configuration file found
✅ Chrome installation found
⚠️ GitHub token not set
Healthcheck passed!Automatically determined ./dist as `staticDistDir`.
Set it explicitly in lighthouserc.json if incorrect.Started a web server on port 64444...
Running Lighthouse 5 time(s) on http://localhost:64444/index.html
Run
Run
Run
Run
Run
Done running Lighthouse!Uploading median LHR of http://localhost:64444/index.html...success!
Open the report at https://storage.googleapis.com/lighthouse-infrastructure.appspot.com/reports/1591716944028-6048.report.html
No GitHub token set, skipping GitHub status check.Done running autorun.
For other configuration options, see Lighthouse CI
setup documentation.
Configure your CI process to run Lighthouse CI
Lighthouse CI can be used with your favorite CI tool. the Configure your CI provider
The Lighthouse CI documentation section contains code samples showing how to incorporate Lighthouse CI into common CI tools configuration files. Specifically, these code samples show how to run Lighthouse CI to collect performance metrics during the CI process.
Using Lighthouse CI to collect performance metrics is a good place to start with performance monitoring. However, advanced users may want to go one step further and use Lighthouse CI to fail builds if they don't meet predefined criteria, such as passing specific Lighthouse audits or meeting all performance budgets. This behavior is configured through the
assert
property of the lighthouserc.js proceedings.
Lighthouse CI supports three levels of assertions:
off: ignore assertionswarn: print faults in stderrerror- Print faults to stderr and exit Lighthouse CI with a non-zero value
exit code
Below is an example of lighthouserc.js configuration that includes assertions. Set claims for Lighthouse performance and accessibility category scores. To test this, add the affirmations shown below to your lighthouserc.js and then run Lighthouse CI again.
module.exports = {
ci: {
collect: {
},
assert: {
assertions: {
'categories:performance': ['warn', {minScore: 1}],
'categories:accessibility': ['error', {minScore: 1}]
}
},
upload: {
},
},
};
The console output it generates looks like this:

For more information on the claims of Lighthouse CI, see the
documentation.
Configure a GitHub Action to Run Lighthouse CI
This section assumes that you are familiar with git, GitHub, and GitHub pull requests.
A GitHub action can be used to run Lighthouse CI. This will generate a new Lighthouse report every time a code change is pushed to any branch in a GitHub repository. Use this in conjunction with a status check
to display these results on every pull request.

-
At the root of your repository, create a directory called
.github / workflows. the
workflows
for your project it will go in this directory. A workflow is a process that runs at a predetermined time (for example, when code is submitted) and is made up of one or more actions.mkdir .github
mkdir .github / workflows -
In
.github / workflowscreate a file calledlighthouse-ci.yaml. This file will contain the settings for a new workflow.touch lighthouse-ci.yaml -
Add the following text to
lighthouse-ci.yaml.yam: Build project and run Lighthouse CI
on: [push]
jobs:
lhci:
yam: Lighthouse CI
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- yam: Use Node.js 10.x
uses: actions/setup-node@v1
with:
node-version: 10.x
- yam: npm install
run: |
npm install
- yam: run Lighthouse CI
run: |
npm install -g @lhci/[email protected]
lhci autorun --upload.target=temporary-public-storage || echo "LHCI failed!"This configuration establishes a workflow consisting of a single job that will run each time new code is submitted to the repository. This job has four steps:
- Check the repository where Lighthouse CI will run
- Install and configure Node
- Install the required npm packages
- Run Lighthouse CI and upload the results to temporary public storage.
-
Commit these changes and submit them to GitHub. If you have followed the steps above correctly, submitting code to GitHub will trigger the execution of the workflow you just added.
-
To confirm that Lighthouse CI has been activated and view the report it generated, go to Behavior tab of your project. You should see the
Build project and run Lighthouse CI workflow listed in your most recent commit.
You can navigate to the Lighthouse report for a particular commit from the Behavior tongue. Click the commitment, click the CI headlight
step of the workflow, then expand the results of the run Lighthouse CI He passed.
You have just configured a GitHub action to run Lighthouse CI. This will be most useful when used in conjunction with a GitHub status check.
Set up a GitHub health check
A health check, if configured, is a message that appears on every RP and typically includes information such as the results of a test or the success of a build.

The following steps explain how to configure a health check for Lighthouse CI.
-
Go to the Lighthouse CI GitHub App Page and click Set up.
-
(Optional) If you are part of multiple organizations on GitHub, choose the organization that owns the repository for which you want to use Lighthouse CI.
-
Please select All repositories if you want to enable Lighthouse CI in all repositories or select Select only repositories if you only want to use it on specific repositories, and then select the repositories. Then click
Install and authorize. -
Copy the token that is displayed. You will use it in the next step.
-
To add the token, navigate to Configurations page of your GitHub repository, click Mysteries, then click Add a new secret.

-
Select the Name field to
LHCI_GITHUB_APP_TOKENand configure the Value
field to the token you copied in the last step and then click the Add secret button. -
The health check is ready to use. To prove it, create a new pull request
or send a confirmation to an existing pull request.
Configure the Lighthouse CI Server
The Lighthouse CI server provides a dashboard to explore the Lighthouse historical reports. It can also act as a long-term private data warehouse for Lighthouse reports.


- Choose which commitments to compare.
- The amount that Lighthouse's score changed between the two commits.
- This section only shows the metrics that have changed between the two commits.
- Regressions are highlighted in pink.
- Improvements are highlighted in blue.
Lighthouse CI Server is best suited for users who are comfortable implementing and managing their own infrastructure.
For information on how to configure the Lighthouse CI server, including recipes for using Heroku and Docker for deployment, see these
instructions.
Know more




