Skip to content

Instantly share code, notes, and snippets.

@mort3za
Created May 29, 2019 15:12
Show Gist options
  • Save mort3za/e959d806a8635a914bcc76c2895014ef to your computer and use it in GitHub Desktop.
Save mort3za/e959d806a8635a914bcc76c2895014ef to your computer and use it in GitHub Desktop.
Run lighthouse programmatically for multiple pages
// yarn add --dev lighthouse cross-env
// in package.json:
// scripts: { "lighthouse-dev": "cross-env NODE_ENV=development node ./lighthouse.js",
// "lighthouse-prod": "cross-env NODE_ENV=production CHROME_FLAGS=--headless node ./lighthouse.js" }
const lighthouse = require('lighthouse')
const chromeLauncher = require('chrome-launcher')
const fs = require('fs')
const mode = process.env.NODE_ENV
const chromeFlags = '-headless'
const outputDirectory = './report_lighthouse'
const ReportGenerator = require('lighthouse/lighthouse-core/report/report-generator')
const config = getConfig()
const sitePages = {
"pages": [
{
"name": "home",
"path": "/"
},
{
"name": "about",
"path": "/about"
},
}
function main () {
asyncForEach(sitePages.pages, async page => {
try {
await launchChromeAndRunLighthouse(page).then(results => {
writeResults(page, results)
})
} catch (error) {
console.log(error)
}
})
}
async function asyncForEach (array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}
function launchChromeAndRunLighthouse (page) {
return new Promise((resolve, reject) => {
const options = {
chromeFlags
}
chromeLauncher.launch({ chromeFlags: options.chromeFlags }).then(chrome => {
options.port = chrome.port
const url = `${config.baseUrl}${page.path}`
lighthouse(url, options, config.lighthouseConfig)
.then(results => {
chrome.kill().then(resolve(results.lhr))
})
.catch(error => {
console.log(error)
reject(error)
})
})
})
}
function writeResults (page, results) {
if (!fs.existsSync(outputDirectory)) {
fs.mkdirSync(outputDirectory)
}
const htmlReport = ReportGenerator.generateReport(results, 'html')
const resultsPath = getReportFilePath(outputDirectory, page.name)
return fs.writeFile(resultsPath, htmlReport, function (err) {
if (err) {
return console.log(err)
}
console.log(`The report for "${page.name}" was saved at ${resultsPath}`)
})
}
function getReportFilePath (outputDirectory, pageName) {
const now = new Date()
return `${outputDirectory}/${pageName}-${now.getFullYear()}-${now.getMonth()}-${now.getDate()}-${now.getHours()}-${now.getMinutes()}-${now.getSeconds()}-${now.getMilliseconds()}.html`
}
function getConfig () {
let configPath
if (mode === 'development') {
configPath = './config/lighthouse.dev.js'
} else if (mode === 'production') {
configPath = './config/lighthouse.prod.js'
}
return require(configPath)
}
main()
@mort3za
Copy link
Author

mort3za commented May 29, 2019

// file: ./config/lighthouse.dev.js
'use strict'

module.exports = {
  baseUrl: 'http://localhost:8080',
  lighthouseConfig: {
    extends: 'lighthouse:default',
    settings: {
      onlyCategories: ['accessibility', 'best-practices', 'seo'],
      skipAudits: ['canonical', 'is-on-https', 'uses-http2']
    }
  }
}

@tkrisztian95
Copy link

tkrisztian95 commented Aug 23, 2021

Thanks for this snippet! It helped me a lot.
I think there is a syntax error somewhere here https://gist.github.com/mort3za/e959d806a8635a914bcc76c2895014ef#file-lighthouse-js-L24:

const sitePages = {
  "pages": [
    {
      "name": "home",
      "path": "/"
    },
    {
      "name": "about",
      "path": "/about"
    }, // <--- A closing array block "]" is missing!
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment