lighthouse-ci-action

repository·main·Indexed 23 days ago

https://github.com/treosh/lighthouse-ci-action

A GitHub Action that integrates Lighthouse CI to audit URLs, test performance budgets, and manage results. It supports auditing live URLs or static directories, validating against assertions in a lighthouserc file, and uploading reports to GitHub Action artifacts, temporary public storage, or private LHCI servers.

Tokens
4.4K
Snippets
14
Records
23
Agent score
79%

What's inside lighthouse-ci-action

  1. Use custom Chrome flags and Lighthouse configurations

    main

    You can customize the audit environment by referencing a lighthouserc file. This file can define Chrome flags via the collect.settings.chromeFlags key or point to a custom Lighthouse configuration file via collect.settings.configPath.

    // lighthouserc.json with Chrome flags
    {
      "ci": {
        "collect": {
          "numberOfRuns": 1,
          "settings": {
            "chromeFlags": "--disable-gpu --no-sandbox --no-zygote"
          }
        }
      }
    }
    
    // lighthouserc.json referencing a custom Lighthouse config
    {
      "ci": {
        "collect": {
          "numberOfRuns": 1,
          "settings": {
            "configPath": "./lighthouse-config.js"
          }
        }
      }
    }
  2. Use Lighthouse CI Action outputs with other actions

    main

    The action provides outputs that can be used by subsequent steps in a workflow. Specifically, you can access links and manifest data to compose powerful workflows, such as sending audit data to a webhook.

          - name: Use output for sending data to API.
            id: LHCIAction
            uses: ./
            with:
              urls: |
                https://treo.sh/
          - name: Webhook
              uses: denar90/webhook-action@0.1.1
              with:
                webhookUrl: ${{secrets.ACTION_WEBHOOK_URL}}
                data: '{ "links": ${{steps.LHCIAction.outputs.links}}, "manifest": ${{steps.LHCIAction.outputs.manifest}} }'
  3. Dynamically generate URLs using GitHub Script

    main

    If your list of URLs is not static, you can use actions/github-script to find files (e.g., via globbing) and generate a newline-separated string of URLs to pass into the urls input of the Lighthouse CI Action.

          - name: Generate URLs
            id: urls
            uses: actions/github-script@v8
            with:
              github-token: ${{ secrets.GITHUB_TOKEN }}
              script: |
                const globber = await glob.create('elements/*/demo/*.html');
                const files = await globber.glob();
                const urls = files
                  .map(x => x.match(/([\w-]+)/)[1])
                  .map(x => `${${{ env.DOMAIN }}}/components/${x}/demo/`)
                  .join('\n');
                core.setOutput('urls', urls);
    
          - name: Lighthouse CI Action
            id: lighthouse
            uses: treosh/lighthouse-ci-action@v12
            with:
              urls: |
                ${{ steps.urls.outputs.urls }}
  4. Configure performance budgets with budget.json

    main

    Define performance budgets using a budget.json file. This file allows you to set limits on resource sizes (e.g., document size or total transfer size) for specific URL paths. The Lighthouse CI Action can then use this file via the budgetPath input to assert that your performance meets these requirements.

    [
      {
        "path": "/*",
        "resourceSizes": [
          { "resourceType": "document", "budget": 18 },
          { "resourceType": "total", "budget": 200 }
        ]
      }
    ]
  5. Upload Lighthouse results to a private LHCI server

    main

    You can upload audit data to a private Lighthouse CI (LHCI) server by providing serverBaseUrl and serverToken as inputs. It is recommended to use GitHub secrets for these values.

    name: Lighthouse
    on: push
    jobs:
      lighthouse:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v6
          - name: Run Lighthouse on urls and upload data to private lhci server
            uses: treosh/lighthouse-ci-action@v12
            with:
              urls: 'https://example.com/'
              serverBaseUrl: ${{ secrets.LHCI_SERVER_URL }}
              serverToken: ${{ secrets.LHCI_SERVER_TOKEN }}
  6. Interpolate environment variables in URLs

    main

    The urls input supports interpolation of process environment variables. This allows you to dynamically construct URLs using values from the env block in your GitHub Action workflow.

          - name: Run Lighthouse and test budgets
            uses: treosh/lighthouse-ci-action@v12
            with:
              urls: |
                https://pr-$PR_NUMBER.staging-example.com/
                https://pr-$PR_NUMBER.staging-example.com/blog
              budgetPath: ./budgets.json
              temporaryPublicStorage: true
            env:
              PR_NUMBER: ${{ github.event.pull_request.number }}
  7. Use Lighthouse CI Action in GitHub Actions

    main

    Integrate Lighthouse CI into your GitHub Actions workflow to audit URLs, test performance budgets, and save results. You can use the action to run audits on every push, specify a list of URLs, and configure how results are stored (e.g., as GitHub Action artifacts or in temporary public storage).

    name: Lighthouse CI
    on: push
    jobs:
      lighthouse:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v6
          - name: Audit URLs using Lighthouse
            uses: treosh/lighthouse-ci-action@v12
            with:
              urls: |
                https://example.com/
                https://example.com/blog
              budgetPath: ./budget.json # test performance budgets
              uploadArtifacts: true # save results as an action artifacts
              temporaryPublicStorage: true # upload lighthouse report to the temporary storage
  8. Run Lighthouse and validate against assertions

    main

    To run Lighthouse audits and automatically fail the workflow if performance metrics do not meet specific thresholds, use a lighthouserc file containing LHCI assertion syntax. You must provide the configPath pointing to your configuration file in the action inputs.

    name: Lighthouse
    on: push
    jobs:
      lighthouse:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v6
          - name: Run Lighthouse on urls and validate with lighthouserc
            uses: treosh/lighthouse-ci-action@v12
            with:
              urls: 'https://exterkamp.codes/'
              configPath: './lighthouserc.json'

    Example lighthouserc.json:

    { "ci": { "assert": { "assertions": { "first-contentful-paint": ["error", { "minScore": 0.6 }] } } } }
  9. Run Lighthouse CI on self-hosted runners

    main

    When using self-hosted runners (e.g., on-premise), ensure you manually set up the necessary environment, such as Node.js and Chrome, before running the action.

        runs-on: [self-hosted, your-custom-label]
        steps:
          - uses: actions/checkout@v6
          - name: install Node.js
          - uses: browser-actions/setup-chrome@latest
          - run: chrome --version
          - uses: actions/setup-node@v5
            with:
              node-version: ${{YOUR_REQUIRED_NODE_JS_VERSION}}
          - name: Audit URLs using Lighthouse
            uses: treosh/lighthouse-ci-action@v12
            with:
              urls: |
                https://example.com/
                https://example.com/blog
  10. Audit a static site without deployment

    main

    To test a static site (e.g., a build folder) without deploying it to a live URL, use the staticDistDir configuration within a lighthouserc file. The action will run a local static webserver to host the files and audit each .html file found in that directory.

    # main.yml
    steps:
      - uses: actions/checkout@v6
      - name: Run Lighthouse against a static dist dir
        uses: treosh/lighthouse-ci-action@v12
        with:
          configPath: './lighthouserc.json'
    # lighthouserc.json
    {
      "ci": {
        "collect": {
          "staticDistDir": "./dist"
        }
      }
    }
  11. Configure Lighthouse CI Action inputs

    main

    The lighthouse-ci-action can be customized using several inputs in your GitHub Actions workflow. Key configuration options include:

    • urls: A newline-separated list of URLs to audit.
    • uploadArtifacts: (default: false) If true, uploads Lighthouse results as GitHub Action artifacts.
    • uploadExtraArgs: String containing extra arguments for the upload command.
    • temporaryPublicStorage: (default: false) If true, uploads reports to a temporary public Google Cloud storage (deleted after 7 days).
    • budgetPath: Path to a budget.json file. The build fails if any URL exceeds the defined budget.
    • runs: (default: 1) Number of runs per URL. Use higher values (e.g., 3) to avoid flaky performance assertions.
    • configPath: Path to a custom lighthouserc file for full control over Lighthouse and LHCI assertions.
    • serverBaseUrl & serverToken: Used to upload results to a private LHCI server instead of public storage.
    • basicAuthUsername & basicAuthPassword: Credentials for LHCI servers protected by basic authentication.
  12. How Lighthouse CI Action works

    main

    The Lighthouse CI Action executes the Lighthouse CI (LHCI) workflow in three distinct stages:

    1. Collect: Runs lhci collect to gather performance data. It can scan a list of urls or a local directory specified by staticDistDir. Results are stored in the .lighthouseci directory.
    2. Assert: Runs lhci assert to validate the collected data against performance budgets or LHCI assertions. This stage is triggered if budgetPath is provided or if the LHCI configuration file contains assertion settings.
    3. Upload: Runs lhci upload to persist the results. It supports uploading to an LHCI Server, Temporary Public Storage, or saving to the local filesystem.

    After the stages complete, the action sets GitHub Action outputs and annotations based on the results found in the .lighthouseci directory.