Generating HTML report in gulp using lighthouse

2.7k views Asked by At

I am using gulp for a project and I added lighthouse to the gulp tasks like this:

gulp.task("lighthouse", function(){
    return launchChromeAndRunLighthouse('http://localhost:3800', flags, perfConfig).then(results => {
      console.log(results);
    });
});

And this is my launchChromeAndRunLighthouse() function

function launchChromeAndRunLighthouse(url, flags = {}, config = null) {
  return chromeLauncher.launch().then(chrome => {
    flags.port = chrome.port;
    return lighthouse(url, flags, config).then(results =>
      chrome.kill().then(() => results));
  });
}

It gives me the json output in command line. I can post my json here and get the report.

Is there any way I can generate the HTML report using gulp ?

You are welcome to start a bounty if you think this question will be helpful for future readers.

4

There are 4 answers

0
Yuvashree Vishwanathan On

You can define the preconfig in the gulp as

const preconfig = {logLevel: 'info', output: 'html', onlyCategories: ['performance','accessibility','best-practices','seo'],port: (new URL(browser.wsEndpoint())).port};

The output option can be used as the html or json or csv. This preconfig is nothing but the configuration for the lighthouse based on how we want it to run and give us the solution.

0
Tobi On

I do

let opts = {
    chromeFlags: ['--show-paint-rects'],
    output: 'html'
}; ...

const lighthouseResults = await lighthouse(urlToTest, opts, config = null);

and later

JSON.stringify(lighthouseResults.lhr)

to get the json

and

lighthouseResults.report.toString('UTF-8'),

to get the html

1
EMC On

I've run into this issue too. I found somewhere in the github issues that you can't use the html option programmatically, but Lighthouse does expose the report generator, so you can write simple file write and open functions around it to get the same effect.

const ReportGenerator = require('../node_modules/lighthouse/lighthouse-core/report/v2/report-generator.js');
3
Nicky On

The answer from @EMC is fine, but it requires multiple steps to generate the HTML from that point. However, you can use it like this (written in TypeScript, should be very similar in JavaScript):

const { write } = await import(root('./node_modules/lighthouse/lighthouse-cli/printer'));

Then call it:

await write(results, 'html', 'report.html');


UPDATE

There have been some changes to the lighthouse repo. I now enable programmatic HTML reports as follows:

const { write } = await import(root('./node_modules/lighthouse/lighthouse-cli/printer'));
const reportGenerator = await import(root('./node_modules/lighthouse/lighthouse-core/report/report-generator'));

// ...lighthouse setup

const raw = await lighthouse(url, flags, config);
await write(reportGenerator.generateReportHtml(raw.lhr), 'html', root('report.html'));

I know it's hacky, but it solves the problem :).