### Install Unlighthouse Globally Source: https://unlighthouse.dev/guide/getting-started Install the CLI globally for frequent use and run it directly. ```bash npm install -g unlighthouse unlighthouse --site example.com ``` -------------------------------- ### Install and run @lhci/cli Source: https://unlighthouse.dev/learn-lighthouse/lhci-vs-unlighthouse Installs the official Google Lighthouse CI CLI globally and executes the autorun command to perform audits. ```bash npm install -g @lhci/cli lhci autorun ``` -------------------------------- ### Example of --auth option Source: https://unlighthouse.dev/integrations/cli.md Shows how to send basic auth with the request. ```bash --auth username:password ``` -------------------------------- ### Quick Start with npm Source: https://unlighthouse.dev/guide/getting-started Run a scan using the npm package manager. ```bash npx unlighthouse --site https://mysite.com ``` -------------------------------- ### Quick Start with pnpm Source: https://unlighthouse.dev/guide/getting-started Run a scan using the pnpm package manager. ```bash pnpm dlx unlighthouse --site https://mysite.com ``` -------------------------------- ### Quick Start with yarn Source: https://unlighthouse.dev/guide/getting-started Run a scan using the yarn package manager. ```bash yarn dlx unlighthouse --site https://mysite.com ``` -------------------------------- ### Install Required Packages Source: https://unlighthouse.dev/learn-lighthouse/playwright Commands to install the necessary dependencies for Playwright and Lighthouse, and to install the Chromium browser. ```bash npm install -D @playwright/test lighthouse npx playwright install chromium ``` -------------------------------- ### Install @unlighthouse/nuxt Source: https://unlighthouse.dev/integrations/nuxt.md Install the @unlighthouse/nuxt module as a dev dependency. ```bash yarn add -D @unlighthouse/nuxt ``` -------------------------------- ### .gitlab-ci.yml Quick Start Audit Static Site Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/gitlab-ci Defines a GitLab CI job named 'lighthouse' that uses the cypress/browsers image with Node 22.12.0 and Chrome 131. It installs @lhci/cli@0.15.x, runs 'lhci autorun', and saves .lighthouseci/ artifacts with a 7-day expiry. ```yaml ```yaml lighthouse: image: cypress/browsers:node-22.12.0-chrome-131.0.6778.204-1-ff-134.0-edge-131.0.2903.112-1 stage: test script: - npm install -g @lhci/cli@0.15.x - lhci autorun artifacts: when: always paths: - .lighthouseci/ expire_in: 7 days ``` ``` -------------------------------- ### Example of --cookies option Source: https://unlighthouse.dev/integrations/cli.md Shows how to send cookies with the request. ```bash --cookies foo=bar;bar=foo ``` -------------------------------- ### Complete PSI API analysis example Source: https://unlighthouse.dev/learn-lighthouse/pagespeed-insights-api/node-example A complete example that loads the API key from environment variables, builds the API URL, fetches data, and extracts performance metrics (performance, accessibility, LCP, CLS, TBT). ```javascript import 'dotenv/config' const API_KEY = process.env.PSI_API_KEY async function analyzeUrl(url) { const apiUrl = new URL('https://www.googleapis.com/pagespeedonline/v5/runPagespeed') apiUrl.searchParams.set('url', url) apiUrl.searchParams.set('key', API_KEY) apiUrl.searchParams.set('strategy', 'mobile') apiUrl.searchParams.append('category', 'performance') apiUrl.searchParams.append('category', 'accessibility') const response = await fetch(apiUrl) if (!response.ok) { console.error(`Failed to analyze ${url}: ${response.status}`) return null } const data = await response.json() const { lighthouseResult } = data return { url, performance: Math.round(lighthouseResult.categories.performance.score * 100), accessibility: Math.round(lighthouseResult.categories.accessibility.score * 100), lcp: lighthouseResult.audits['largest-contentful-paint'].numericValue, cls: lighthouseResult.audits['cumulative-layout-shift'].numericValue, tbt: lighthouseResult.audits['total-blocking-time'].numericValue, } } const result = await analyzeUrl('https://example.com') console.log(result) ``` -------------------------------- ### ESM webpack.config.js example with Unlighthouse plugin Source: https://unlighthouse.dev/integrations/webpack.md Extend your webpack configuration by importing and adding the Unlighthouse plugin. When you run the webpack app, the client URL is provided, and Unlighthouse starts only after you visit it. ```js import Unlighthouse from '@unlighthouse/webpack' export default { // ... plugins: [ Unlighthouse({ // config }), ], } ``` -------------------------------- ### Complete valid robots.txt example Source: https://unlighthouse.dev/learn-lighthouse/seo/robots-txt A complete valid robots.txt example with multiple user agents, disallow rules, and sitemap directives. Use as a reference for a fully compliant file. ```txt User-agent: * Allow: / Disallow: /admin/ Disallow: /api/ Disallow: /private/ Disallow: /*.json$ User-agent: GPTBot Disallow: / User-agent: CCBot Disallow: / Sitemap: https://example.com/sitemap.xml Sitemap: https://example.com/sitemap-blog.xml ``` -------------------------------- ### Example of --include-urls option Source: https://unlighthouse.dev/integrations/cli.md Shows how to include relative paths (string or regex) for scanning. ```bash unlighthouse --site unlighthouse.dev --include-urls /guide/.* ``` -------------------------------- ### Install Dependencies for Async PSI Analysis Source: https://unlighthouse.dev/learn-lighthouse/pagespeed-insights-api/python-example Install the necessary packages to perform asynchronous requests and rate limiting. ```bash pip install aiohttp aiolimiter ``` -------------------------------- ### Meta description examples by page type Source: https://unlighthouse.dev/learn-lighthouse/seo/meta-description Example meta description tags for different page types: homepage, product page, blog post, and documentation. Each example shows a concise, keyword-rich description with a value proposition or call to action. ```html ``` -------------------------------- ### Install Unlighthouse CLI and Puppeteer Source: https://unlighthouse.dev/integrations/ci.md Install the CLI and Puppeteer globally to ensure a compatible Chromium binary is available in the CI environment. ```bash npm install -g @unlighthouse/cli puppeteer ``` -------------------------------- ### Example of --default-query-params option Source: https://unlighthouse.dev/integrations/cli.md Shows how to send default query params with the request. ```bash --default-query-params foo=bar,bar=foo ``` -------------------------------- ### Dynamic meta description with Vanilla JS and React Helmet Source: https://unlighthouse.dev/learn-lighthouse/seo/meta-description Dynamic meta description setup for SPAs and dynamic content. The Vanilla JS function setMetaDescription creates or updates the meta tag. The React Helmet example sets the description using product data. Use this when the description depends on runtime data. ```js // Vanilla JS // React Helmet import { Helmet } from 'react-helmet' function setMetaDescription(content) { let meta = document.querySelector('meta[name="description"]') if (!meta) { meta = document.createElement('meta') meta.name = 'description' document.head.appendChild(meta) } meta.content = content } function ProductPage({ product }) { return ( <> {/* page content */} ) } ``` -------------------------------- ### Install Chrome and Run Lighthouse CI Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/gitlab-ci GitLab CI script that installs Chrome manually and runs Lighthouse CI. Use this when the default image lacks Chrome and you cannot use the cypress/browsers image. ```yaml script: - apt-get update - apt-get install -y wget gnupg - wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | gpg --dearmor -o /usr/share/keyrings/google-chrome.gpg - echo "deb [signed-by=/usr/share/keyrings/google-chrome.gpg] http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google.list - apt-get update - apt-get install -y google-chrome-stable - npm install -g @lhci/cli@0.15.x - lhci autorun ``` -------------------------------- ### Example of --extra-headers option Source: https://unlighthouse.dev/integrations/cli.md Shows how to send extra headers with the request. ```bash --extra-headers foo=bar,bar=foo ``` -------------------------------- ### Install Chrome on CI Runner Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/troubleshooting Commands to install Chrome on Ubuntu/Debian systems or via Puppeteer. ```bash # Ubuntu/Debian sudo apt-get update sudo apt-get install -y wget gnupg wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add - sudo sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' sudo apt-get update sudo apt-get install -y google-chrome-stable # Or use puppeteer's Chrome npx @puppeteer/browsers install chrome@stable ``` -------------------------------- ### Replace heavy dependencies example Source: https://unlighthouse.dev/learn-lighthouse/lcp/unused-javascript Compare syntax for heavy libraries like moment with lighter alternatives like dayjs. ```text // After: dayjs (2KB) import dayjs from 'dayjs' // Before: moment (300KB) import moment from 'moment' moment().format('YYYY-MM-DD') dayjs().format('YYYY-MM-DD') ``` -------------------------------- ### Basic Lighthouse Integration Example Source: https://unlighthouse.dev/learn-lighthouse/playwright A complete script that launches a browser, navigates to a URL, runs a Lighthouse audit, saves an HTML report, and logs category scores. ```js import { writeFileSync } from 'node:fs' import { chromium } from '@playwright/test' import lighthouse from 'lighthouse' const PORT = 9222 async function runLighthouseAudit(url) { // Launch Chrome with remote debugging enabled const browser = await chromium.launch({ args: [`--remote-debugging-port=${PORT}`], }) const page = await browser.newPage() await page.goto(url, { waitUntil: 'networkidle' }) // Run Lighthouse audit const result = await lighthouse(url, { port: PORT, output: 'html', logLevel: 'error', }) // Save HTML report writeFileSync('lighthouse-report.html', result.report) // Extract scores const { categories } = result.lhr console.log('Performance:', Math.round(categories.performance.score * 100)) console.log('Accessibility:', Math.round(categories.accessibility.score * 100)) console.log('Best Practices:', Math.round(categories['best-practices'].score * 100)) console.log('SEO:', Math.round(categories.seo.score * 100)) await browser.close() return result.lhr } runLighthouseAudit('https://example.com') ``` -------------------------------- ### Install @googleapis/pagespeedonline Source: https://unlighthouse.dev/learn-lighthouse/pagespeed-insights-api/node-example Install the official Google PageSpeed Insights Node.js client package via npm. ```bash npm install @googleapis/pagespeedonline ``` -------------------------------- ### Install @unlighthouse/vite with yarn Source: https://unlighthouse.dev/integrations/vite.md Install the Vite integration package as a dev dependency. This is the first step to using Unlighthouse with Vite. ```bash yarn add -D @unlighthouse/vite ``` -------------------------------- ### Complete LCP image optimization example Source: https://unlighthouse.dev/learn-lighthouse/lcp/prioritize-lcp-image Combines preload in the head and an optimized img tag with fetchpriority, loading, decoding, and dimensions. ```html Descriptive alt text ``` -------------------------------- ### Force specific port in package.json Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/troubleshooting Ensure the server starts on a predictable port by passing flags to the start command. ```bash # package.json { "scripts": { "serve": "vite preview --port 8080 --strictPort" } } ``` -------------------------------- ### Install Chromium and dependencies in CI Source: https://unlighthouse.dev/learn-lighthouse/playwright/ci-cd Installs only the Chromium browser and necessary system dependencies for the CI job, avoiding binary caching. ```yaml - name: Install Chromium and system dependencies run: npx playwright install chromium --with-deps ``` -------------------------------- ### Server Command Configuration Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/configuration Start a local server automatically before collection. The server process is terminated once the collection completes. ```js const config4 = { ci: { collect: { startServerCommand: 'npm run serve', startServerReadyPattern: 'Server listening on', startServerReadyTimeout: 10000, // ms url: ['http://localhost:8080/'], numberOfRuns: 3, }, }, } ``` -------------------------------- ### Assert presets configuration Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/configuration Defines the `assert` configuration with a preset. The example shows `lighthouse:all`, with commented alternatives for `lighthouse:recommended` and `lighthouse:no-pwa`. ```javascript const config7 = { ci: { assert: { // All Lighthouse audits must pass preset: 'lighthouse:all', // OR recommended audits only // preset: 'lighthouse:recommended', // OR recommended excluding PWA audits // preset: 'lighthouse:no-pwa', }, }, } ``` -------------------------------- ### Compare unminified and minified code Source: https://unlighthouse.dev/learn-lighthouse/lcp/unminified-javascript Example showing the difference between readable unminified code and dense, minified code. ```js // Unminified (don't ship this) function calculateTotal(items) { let total = 0 for (const item of items) { total += item.price * item.quantity } return total } ``` ```text function calculateTotalMinified(e){let t=0;for(const l of e)t+=l.price*l.quantity;return t} ``` -------------------------------- ### Lighthouse CI Configuration for Local Servers Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/github-actions Configuration object for apps requiring a local server, specifying the start command and the local URL to audit. ```js const config3 = { ci: { collect: { startServerCommand: 'npm run start', url: ['http://localhost:3000/'], }, upload: { target: 'temporary-public-storage', }, }, } ``` -------------------------------- ### Example of --urls option Source: https://unlighthouse.dev/integrations/cli.md Shows how to specify explicit relative paths to scan, disabling the link crawler. ```bash unlighthouse --site unlighthouse.dev --urls /guide,/api,/config ``` -------------------------------- ### JSON Report Sample Source: https://unlighthouse.dev/guide/guides/generating-static-reports.md An example of the output generated by the json reporter. ```json [ { "path": "/", "score": 0.97, "performance": 0.87, "accessibility": 1, "best-practices": 1, "seo": 1 }, { "path": "/blog", "score": 0.98, "performance": 0.91, "accessibility": 1, "best-practices": 1, "seo": 1 }, { "path": "/blog/2023-february", "score": 0.91, "performance": 0.65, "accessibility": 1, "best-practices": 1, "seo": 1 }, { "path": "/blog/modern-package-development", "score": 0.9, "performance": 0.61, "accessibility": 0.97, "best-practices": 1, "seo": 1 }, { "path": "/blog/scale-your-vue-components", "score": 0.87, "performance": 0.51, "accessibility": 0.97, "best-practices": 1, "seo": 1 }, { "path": "/blog/vue-automatic-component-imports", "score": 0.88, "performance": 0.53, "accessibility": 0.97, "best-practices": 1, "seo": 1 }, { "path": "/blog/vue-use-head-v1", "score": 0.97, "performance": 0.9, "accessibility": 0.97, "best-practices": 1, "seo": 1 }, { "path": "/projects", "score": 0.94, "performance": 0.77, "accessibility": 1, "best-practices": 1, "seo": 1 }, { "path": "/sponsors", "score": 0.97, "performance": 0.88, "accessibility": 1, "best-practices": 1, "seo": 1 }, { "path": "/talks", "score": 0.94, "performance": 0.74, "accessibility": 1, "best-practices": 1, "seo": 1 } ] ``` -------------------------------- ### Configure Unlighthouse plugin with scanner device Source: https://unlighthouse.dev/integrations/vite.md Example configuration for the Unlighthouse plugin, setting the scanner device to 'desktop' to simulate a desktop device. ```ts import Unlighthouse from '@unlighthouse/vite' import { defineConfig } from 'vite' export default defineConfig({ plugins: [ Unlighthouse({ scanner: { // simulate a desktop device device: 'desktop', } }) ] }) ``` -------------------------------- ### Run Audit with Authenticated Session Source: https://unlighthouse.dev/learn-lighthouse/playwright/authentication Example of a test case that runs after authentication has been handled by the project dependency setup. ```ts test('dashboard performance', async ({ page }) => { // Page is already authenticated! await page.goto('https://app.example.com/dashboard') // Connect Lighthouse to this authenticated session // (Use the port and disableStorageReset pattern) }) ``` -------------------------------- ### Get All Category Scores from PSI API Source: https://unlighthouse.dev/learn-lighthouse/pagespeed-insights-api/python-example Fetches performance, accessibility, SEO, and best-practices scores in a single API call. The function returns a dictionary with scores rounded to integers (0-100). The example output shows sample scores. ```python import requests def fetch_all_categories(url: str, api_key: str) -> dict: response = requests.get( 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed', params={ 'url': url, 'key': api_key, 'category': ['performance', 'accessibility', 'seo', 'best-practices'] } ) data = response.json() categories = data['lighthouseResult']['categories'] return { key: round(value['score'] * 100) for key, value in categories.items() } scores = fetch_all_categories('https://example.com', API_KEY) print(scores) # {'performance': 87, 'accessibility': 92, 'seo': 100, 'best-practices': 95} ``` -------------------------------- ### GitHub Actions workflow for Lighthouse Source: https://unlighthouse.dev/learn-lighthouse/playwright/ci-cd A complete GitHub Actions workflow that sets up Node.js, installs dependencies, builds the project, and runs Playwright tests. ```yaml name: Lighthouse CI on: pull_request: branches: [main] push: branches: [main] jobs: lighthouse: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: npm - run: npm ci - run: npx playwright install chromium --with-deps - run: npm run build # Playwright starts the server automatically! - name: Run Lighthouse run: npx playwright test ``` -------------------------------- ### TBT Contribution Calculation Examples Source: https://unlighthouse.dev/learn-lighthouse/inp/total-blocking-time Illustrates how Lighthouse calculates TBT contribution by subtracting the 50ms threshold from task durations exceeding that limit. ```text Task duration: 70ms → TBT contribution: 20ms (70 - 50) Task duration: 200ms → TBT contribution: 150ms (200 - 50) Task duration: 45ms → TBT contribution: 0ms (under threshold) ``` -------------------------------- ### Run Unlighthouse scan on example.com Source: https://unlighthouse.dev/glossary Use npx to run Unlighthouse and audit all metrics across your entire website in a single scan. Replace example.com with your site's URL. ```bash npx unlighthouse --site example.com ``` -------------------------------- ### createUnlighthouse() Source: https://unlighthouse.dev/api-doc.md Initializes Unlighthouse with the provided configuration and an optional provider. This is the entry point to using Unlighthouse. ```APIDOC ## createUnlighthouse() ### Description Initializes Unlighthouse with the provided configuration and an optional provider. This is the entry point to using Unlighthouse. ### Method createUnlighthouse ### Signature `(userConfig: UserConfig, provider?: Provider) => Promise` ### Parameters - **userConfig** (UserConfig) - Required - Configuration for Unlighthouse. - **provider** (Provider) - Optional - Custom provider implementation. ### Request Example ``` import { createUnlighthouse } from '@unlighthouse/core' createUnlighthouse( // config { configFile: 'mysite.config.ts' }, // provider { name: 'custom', // some custom implementation to find the route definitions routeDefinitions: () => generateRouteDefinitions(), } ) ``` ### Response Returns a Promise that resolves to an `UnlighthouseContext`. ``` -------------------------------- ### Create auth.setup.ts for Authentication Source: https://unlighthouse.dev/learn-lighthouse/playwright/authentication Performs the login process and saves the authentication state to a file for subsequent tests to use. ```ts import { test as setup } from '@playwright/test' setup('authenticate', async ({ page }) => { await page.goto('https://app.example.com/login') // ... perform login ... await page.context().storageState({ path: 'playwright/.auth/user.json' }) }) ``` -------------------------------- ### Describe the Destination with API Documentation Links Source: https://unlighthouse.dev/learn-lighthouse/seo/link-text Ensure the link text clearly identifies the destination, such as documentation or API guides. ```html Learn more Get started with our API ``` -------------------------------- ### Self-Referencing Canonical Example Source: https://unlighthouse.dev/learn-lighthouse/seo/canonical Example of a self-referencing canonical tag for a specific blog post. ```html ``` -------------------------------- ### Create server context for UI Source: https://unlighthouse.dev/guide/getting-started/how-it-works.md Initializes the local web server and sets the server context for the Unlighthouse UI client. ```ts // Create server for the UI client const { server, app } = await createServer() await unlighthouse.setServerContext({ url: server.url, server: server.server, app }) ``` -------------------------------- ### GitHub Actions workflow for Netlify deployment Source: https://unlighthouse.dev/guide/guides/generating-static-reports.md A GitHub Actions workflow that installs dependencies, generates a static Unlighthouse report, and deploys the output to Netlify. ```yaml name: Assertions and static report on: workflow_dispatch: jobs: demo: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - name: Install Dependencies run: npm add -g @unlighthouse/cli puppeteer - name: Unlighthouse assertions and client run: unlighthouse-ci --site --build-static - name: Deploy report to Netlify uses: nwtgck/actions-netlify@v3.0 with: publish-dir: ./.unlighthouse production-branch: main production-deploy: true github-token: ${{ secrets.GITHUB_TOKEN }} deploy-message: New Release Deploy from GitHub Actions enable-pull-request-comment: false enable-commit-comment: true overwrites-pull-request-comment: true env: NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} NETLIFY_SITE_ID: ${{ secrets.NETLIFY_DEMO_SITE_ID }} timeout-minutes: 1 ``` -------------------------------- ### Run Lighthouse CI Locally for Baseline Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/budgets Collect performance data locally and run assertions against the recommended preset to identify current metric values before setting budgets. ```bash lhci collect --url=http://localhost:3000 lhci assert --preset=lighthouse:recommended ``` -------------------------------- ### Aggregation Configuration Example Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/budgets Shows the full CI configuration structure with assert, collect, and upload sections. The collect section sets numberOfRuns to 5, and upload uses temporary-public-storage. ```javascript const config9 = { ci: { assert: { assertions: { /* ... */ } }, collect: { numberOfRuns: 5 }, upload: { target: 'temporary-public-storage' } } } ``` -------------------------------- ### Configure startServerReadyPattern Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/troubleshooting Use startServerReadyPattern and startServerReadyTimeout to ensure the server is fully initialized before Lighthouse begins auditing. ```js // lighthouserc.js const config9 = { ci: { collect: { startServerCommand: 'npm run serve', startServerReadyPattern: 'Local:.*http://localhost:8080', // Wait for this log startServerReadyTimeout: 30000, // 30s timeout url: ['http://localhost:8080'] } } } ``` -------------------------------- ### Install Unlighthouse webpack integration with yarn Source: https://unlighthouse.dev/integrations/webpack.md Install the @unlighthouse/webpack package as a development dependency to add Lighthouse auditing to a webpack-based project. ```bash yarn add -D @unlighthouse/webpack ``` -------------------------------- ### Install Chrome dependencies in GitHub Actions Source: https://unlighthouse.dev/learn-lighthouse/playwright/troubleshooting Use the --with-deps flag to install necessary system dependencies for Chromium in CI environments. ```yaml - name: Install Chrome run: npx playwright install chromium --with-deps ``` -------------------------------- ### Examples for common embed types Source: https://unlighthouse.dev/learn-lighthouse/accessibility/frame-title Provides iframe examples for Google Maps, social media embeds, third-party widgets, and advertising, each with a descriptive title attribute. ```html ``` -------------------------------- ### Build Nuxt project Source: https://unlighthouse.dev/learn-lighthouse/lcp/unminified-javascript Use the Nuxt CLI to build the project and check bundle sizes. ```bash npx nuxi build ``` -------------------------------- ### Restructure to Avoid the Conflict Source: https://unlighthouse.dev/learn-lighthouse/accessibility/aria-hidden-focus Rethink HTML structure to avoid hiding focusable elements. The before example shows a hidden icon and link, the after example only hides the decorative icon. ```html
Download
``` -------------------------------- ### Chrome Won't Launch Error Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/gitlab-ci Error message shown when Chrome cannot be launched because it is not installed or not found at the expected path. Use the cypress/browsers image or install Chrome manually to resolve. ```text Failed to launch Chrome: spawn /usr/bin/google-chrome ENOENT ``` -------------------------------- ### Verify build output with ls Source: https://unlighthouse.dev/learn-lighthouse/lcp/unminified-javascript Use the ls command to list files in your distribution directory to verify the presence of minified assets. ```bash ls -la dist/assets/*.js ``` -------------------------------- ### Initialize Unlighthouse with createUnlighthouse Source: https://unlighthouse.dev/api-doc.md The entry point for initializing Unlighthouse with a user configuration and an optional custom provider. ```typescript import { createUnlighthouse } from '@unlighthouse/core' createUnlighthouse( // config { configFile: 'mysite.config.ts' }, // provider { name: 'custom', // some custom implementation to find the route definitions routeDefinitions: () => generateRouteDefinitions(), } ) ``` -------------------------------- ### Add tabindex="-1" to Focusable Descendants Source: https://unlighthouse.dev/learn-lighthouse/accessibility/aria-hidden-focus Removes focusable elements from the tab order while keeping them hidden from assistive technology. The before example shows the problem, the after example shows the fix. ```html ``` -------------------------------- ### Configure Lighthouse CI with Environment Variables Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/configuration Set configuration options using the LHCI_ prefix with double underscores for nesting. These values override those defined in configuration files. ```bash # Equivalent to ci.collect.numberOfRuns LHCI_COLLECT__NUMBER_OF_RUNS=5 # Equivalent to ci.upload.serverBaseUrl LHCI_UPLOAD__SERVER_BASE_URL=https://lhci.example.com # Equivalent to ci.upload.token LHCI_UPLOAD__TOKEN=your-secret-token ``` -------------------------------- ### createServer() usage with @unlighthouse/server Source: https://unlighthouse.dev/api-doc.md Creates an h3 app using listhen as a web server to host the API and client. The returned server is a listhen instance and app is an h3 instance. Requires setting the server context before calling start(). ```javascript import { createServer } from '@unlighthouse/server' // ... const { server, app } = await createServer() // server is an instance of listhen, app is an instance of h3 await unlighthouse.setServerContext({ url: server.url, server: server.server, app }) await unlighthouse.start() ``` -------------------------------- ### Run Unlighthouse via CLI Source: https://unlighthouse.dev/integration-deprecations.md Use the CLI as an alternative to deprecated build tool integrations. Replace the site URL with your specific development site address. ```bash npx unlighthouse --site localhost:3000 ``` -------------------------------- ### CSV Expanded Report Sample Source: https://unlighthouse.dev/guide/guides/generating-static-reports.md An example of the output generated by the csvExpanded reporter. ```csv URL,Score,Performance,Accessibility,Best Practices,SEO,Largest Contentful Paint,Cumulative Layout Shift,FID,Blocking,Color Contrast,Headings,Image Alts,Link Names,Errors,Inspector Issues,Images Responsive,Image Aspect Ratio,Indexable,Tap Targets "/",93,72,100,100,100,3211.44,0,290.36,562.29,1,1,1,1,1,1,1,1,1,1 "/blog",94,77,100,100,100,3911.7,0,205.57,260.03,1,1,1,1,1,1,1,1,1,1 "/blog/2023-april",88,51,100,100,100,4925.84,0,311.24,797.95,1,1,1,1,1,1,1,1,1,1 "/blog/2023-february",96,82,100,100,100,3207.98,0,209.96,302.01,1,1,1,1,1,1,1,1,1,1 "/blog/nuxt-3-migration-cheatsheet",85,43,97,100,100,4373.88,0,1581.52,2820.75,0,1,1,1,1,1,1,1,1,1 "/blog/vue-automatic-component-imports",93,74,97,100,100,1696.51,0,793.36,1314.27,0,1,1,1,1,1,1,1,1,1 "/blog/vue-use-head-v1",82,30,97,100,100,8053.8,0,379.59,1127.99,0,1,1,1,1,1,1,1,1,1 "/projects",92,66,100,100,100,3666.86,0,322.48,625.51,1,1,1,1,1,1,1,1,1,1 "/sponsors",92,69,100,100,100,4438.15,0,362.62,408.63,1,1,1,1,1,1,1,1,1,1 "/talks",98,90,100,100,100,864.86,0,390.93,427.94,1,1,1,1,1,1,1,1,1,1 ``` -------------------------------- ### Compress images with sharp-cli, ImageMagick, and cwebp Source: https://unlighthouse.dev/learn-lighthouse/lcp/large-images Command-line tools to compress images to WebP at quality 80. sharp-cli, ImageMagick convert, and Google's cwebp. ```bash npx sharp-cli hero.jpg -o hero.webp -- webp -q 80 convert hero.jpg -quality 80 hero.webp # Cwebp (Google) cwebp -q 80 hero.jpg -o hero.webp ``` -------------------------------- ### CORS Policy Block Error Source: https://unlighthouse.dev/learn-lighthouse/best-practices/inspector-issues Example of a CORS error message encountered in the console. ```text Access to fetch at 'https://api.example.com/data' from origin 'https://mysite.com' has been blocked by CORS policy ``` -------------------------------- ### Recommended Production Configuration Source: https://unlighthouse.dev/guide/recipes/improving-accuracy.md Combine multiple samples, network throttling, and single-worker concurrency for the most accurate performance results in production. ```ts export default defineUnlighthouseConfig({ scanner: { samples: 5, throttle: true, }, puppeteerClusterOptions: { maxConcurrency: 1, }, }) ``` -------------------------------- ### Create new project via API Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/troubleshooting Create a new project on your LHCI server using an admin token if the build token is lost. ```bash curl -X POST https://your-lhci-server.com/v1/projects \ -H "Authorization: Bearer $LHCI_ADMIN_TOKEN" \ -H "Content-Type: application/json" \ -d '{"name": "my-project", "externalUrl": "https://github.com/user/repo"}' ``` -------------------------------- ### HTML nested heading hierarchy Source: https://unlighthouse.dev/learn-lighthouse/accessibility/heading-order Example of a properly nested heading structure for sections and subsections. ```html

Product Catalog

Electronics

Phones

Laptops

Clothing

Shirts

Pants

``` -------------------------------- ### Basic Lighthouse CI GitHub Actions workflow (lighthouse.yml) Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/github-actions Basic GitHub Actions workflow that runs Lighthouse CI on every push. Requires Node 20 and uses the pre-installed Chrome on Ubuntu runners. Set fetch-depth to 20 or higher to avoid 'Could not find hash' errors from shallow clones. ```yaml name: Lighthouse CI on: [push] jobs: lighthouse: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 20 # Required for base branch comparison - uses: actions/setup-node@v4 with: node-version: 20 - run: npm ci && npm run build - run: npm install -g @lhci/cli@0.15.x - run: lhci autorun ``` -------------------------------- ### Example of --exclude-urls option Source: https://unlighthouse.dev/integrations/cli.md Shows how to exclude relative paths (string or regex) from scanning. ```bash unlighthouse --site unlighthouse.dev --exclude-urls /guide/.*,/api/.* ``` -------------------------------- ### Simple Performance Budget Source: https://unlighthouse.dev/integrations/ci.md Set a single threshold for all categories on all pages. ```bash # Fail if ANY category on ANY page < 75 unlighthouse-ci --site example.com --budget 75 ``` -------------------------------- ### Start Unlighthouse in CLI mode Source: https://unlighthouse.dev/guide/getting-started/how-it-works.md Initiates the scanning process immediately when running in CLI mode. ```ts // CLI mode - starts immediately unlighthouse.start() ``` -------------------------------- ### Install system dependencies in Dockerfile Source: https://unlighthouse.dev/learn-lighthouse/playwright/troubleshooting Required system libraries for running Chromium inside a Docker container. ```dockerfile RUN apt-get update && apt-get install -y \ libnss3 \ libatk1.0-0 \ libatk-bridge2.0-0 \ libcups2 \ libdrm2 \ libxkbcommon0 \ libxcomposite1 \ libxdamage1 \ libxrandr2 \ libgbm1 \ libasound2 ``` -------------------------------- ### Common robots.txt Mistakes Source: https://unlighthouse.dev/learn-lighthouse/seo/is-crawlable Examples of overly restrictive patterns that can accidentally block important site sections. ```txt Disallow: /*?* Disallow: /*.pdf$ Disallow: /staging # Also matches /staging-guide, /staging-area ``` -------------------------------- ### Next.js bundle analysis command Source: https://unlighthouse.dev/learn-lighthouse/lcp/unused-javascript Run the build process with the bundle analyzer enabled. ```bash ANALYZE=true npm run build ``` -------------------------------- ### CSP Violation Error Source: https://unlighthouse.dev/learn-lighthouse/best-practices/inspector-issues Example of a console error indicating a script was blocked by the Content Security Policy. ```text Refused to load the script 'https://analytics.example.com/track.js' because it violates the Content-Security-Policy directive: "script-src 'self'" ``` -------------------------------- ### Nuxt Automatic SSR Source: https://unlighthouse.dev/learn-lighthouse/lcp/client-side-rendering Uses the script setup pattern to fetch data on the server for automatic SSR. ```html ``` -------------------------------- ### Optimizing image quality with cwebp Source: https://unlighthouse.dev/learn-lighthouse/lcp/large-images Demonstrates the impact of quality settings on image output; avoid setting quality too low to prevent visible artifacts. ```bash cwebp -q 30 hero.jpg -o hero.webp # Will look bad cwebp -q 80 hero.jpg -o hero.webp ``` -------------------------------- ### Common Canonical Link Tag Issues Source: https://unlighthouse.dev/learn-lighthouse/seo/canonical Examples of invalid, relative, or conflicting canonical link tags that should be avoided. ```html ``` -------------------------------- ### Dynamic hreflang URL generation Source: https://unlighthouse.dev/learn-lighthouse/seo/hreflang JavaScript example for constructing absolute URLs when generating hreflang tags dynamically. ```javascript const baseUrl = 'https://example.com' const hreflangs = [ { lang: 'en', path: '/' }, { lang: 'es', path: '/es/' }, { lang: 'fr', path: '/fr/' }, ] hreflangs.map(h => ({ rel: 'alternate', hreflang: h.lang, href: `${baseUrl}${h.path}`, })) ``` -------------------------------- ### Run Unlighthouse CLI to scan entire site Source: https://unlighthouse.dev/tools/bulk-pagespeed Use this command to scan an entire site with Unlighthouse CLI, which automatically discovers and audits hundreds of pages. This is recommended for comprehensive site-wide analysis instead of bulk testing a limited number of URLs. ```bash $ npx unlighthouse --site example.com ``` -------------------------------- ### Complete example: picture with AVIF, WebP, and JPEG fallback Source: https://unlighthouse.dev/learn-lighthouse/lcp/large-images Full responsive picture element with AVIF, WebP, and JPEG sources, including srcset, sizes, width/height, fetchpriority, and decoding. ```html Descriptive alt text ``` -------------------------------- ### Check CSS for HTTP URLs Source: https://unlighthouse.dev/learn-lighthouse/best-practices/is-on-https Example of a hardcoded HTTP URL in a CSS background property that should be updated to HTTPS. ```css /* Check your CSS files for http:// URLs */ background: url(http://example.com/bg.png); ``` -------------------------------- ### Run Lighthouse CLI: npx lighthouse --output=json Source: https://unlighthouse.dev/learn-lighthouse/pagespeed-insights-vs-lighthouse Runs Lighthouse locally from the command line, outputting JSON. Use this to generate lab-only performance metrics on your own machine without a Google account. ```bash npx lighthouse https://example.com --output=json ``` -------------------------------- ### CORS Error Console Output Source: https://unlighthouse.dev/learn-lighthouse/best-practices/errors-in-console Example console output for a CORS error, indicating the blocked cross-origin request. ```text Access to fetch at 'https://api.example.com' from origin 'https://yoursite.com' has been blocked by CORS policy ``` -------------------------------- ### Run Unlighthouse in desktop mode via CLI Source: https://unlighthouse.dev/guide/guides/device.md Use the --desktop flag to override default mobile emulation and scan pages using a desktop viewport. ```bash npx unlighthouse --site https://example.com --desktop ``` -------------------------------- ### Usage of Dynamic Heading Component in Nuxt/Vue Source: https://unlighthouse.dev/learn-lighthouse/accessibility/heading-order Example of nesting the dynamic heading component to maintain a logical hierarchy. ```html Products Electronics ``` -------------------------------- ### Lighthouse CI Configuration for Live URLs Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/github-actions Configuration object for auditing already deployed websites using temporary public storage. ```js const config2 = { ci: { collect: { url: ['https://example.com/', 'https://example.com/about'], }, upload: { target: 'temporary-public-storage', }, }, } ``` -------------------------------- ### Configure routerPrefix in unlighthouse.config.ts Source: https://unlighthouse.dev/api-doc/config.md Example of setting the routerPrefix to serve the Unlighthouse application from a specific URL path prefix. ```typescript import { defineUnlighthouseConfig } from 'unlighthouse/config' export default defineUnlighthouseConfig({ routerPrefix: '/__unlighthouse', }) ``` -------------------------------- ### Register task-complete hook Source: https://unlighthouse.dev/api-doc.md Example of accessing the hooks property from the Unlighthouse context and registering a listener for the task-complete event. ```typescript import { useUnlighthouse } from '@unlighthouse/core' const { hooks } = useUnlighthouse() hooks.hook('task-complete', (path, response) => { console.log('task is finished at path', path) }) ``` -------------------------------- ### Verify Next.js production build Source: https://unlighthouse.dev/learn-lighthouse/lcp/unminified-javascript Run the build command to verify the production bundle size in Next.js. ```bash npm run build # + /_app 87 kb 87 kb ``` -------------------------------- ### Single Page App config with staticDistDir and performance assertions Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/configuration Configure Lighthouse CI for a single-page app built to a static directory. Uses the 'lighthouse:no-pwa' preset and asserts performance, FCP, and Speed Index thresholds. Uploads results to temporary public storage. ```js const config19 = { ci: { collect: { staticDistDir: './build', URL: ['http://localhost/index.html'], numberOfRuns: 5, }, assert: { preset: 'lighthouse:no-pwa', assertions: { 'categories:performance': ['error', { minScore: 0.9 }], 'first-contentful-paint': ['error', { maxNumericValue: 2000 }], 'speed-index': ['error', { maxNumericValue: 3000 }], }, }, upload: { target: 'temporary-public-storage', }, }, } ``` -------------------------------- ### Run Unlighthouse via npx Source: https://unlighthouse.dev/learn-lighthouse/bulk-lighthouse-testing Execute an audit on a specific site using npx without requiring a global installation. ```bash npx unlighthouse --site https://your-site.com ``` -------------------------------- ### maxNumericValue Threshold Configuration Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/budgets Uses maxNumericValue for millisecond/byte values. Value must be at or below the threshold; FCP example allows up to 1800ms. ```javascript const config8 = { assertions: { 'first-contentful-paint': ['error', { maxNumericValue: 1800 }], 'speed-index': ['error', { maxNumericValue: 3000 }], 'total-byte-weight': ['warn', { maxNumericValue: 1500000 }] } } ``` -------------------------------- ### Configure Filesystem Upload Target Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/gitlab-ci Lighthouse CI configuration that sets the upload target to filesystem and specifies the output directory. Use this to generate reports locally. ```js const config10 = { upload: { target: 'filesystem', outputDir: './lhci-reports' } } ``` -------------------------------- ### CSP Violation Console Output Source: https://unlighthouse.dev/learn-lighthouse/best-practices/errors-in-console Example console output for a Content Security Policy violation, showing the directive that was violated. ```text Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'" ``` -------------------------------- ### Use lighthouse:no-pwa Preset Source: https://unlighthouse.dev/learn-lighthouse/lighthouse-ci/budgets Identical to the recommended preset but excludes Progressive Web App audits. ```js const config5 = { ci: { assert: { preset: 'lighthouse:no-pwa' } } } ``` -------------------------------- ### Register visited-client hook Source: https://unlighthouse.dev/api-doc.md Triggered when a user visits the UI path for the first time, useful for starting the worker on-demand. ```typescript // only start when the user wants to see the client hooks.hookOnce('visited-client', () => { unlighthouse.start() }) ```