Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating HTML report in gulp using lighthouse

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.

like image 315
bhansa Avatar asked Sep 13 '17 13:09

bhansa


3 Answers

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');
like image 122
EMC Avatar answered Nov 04 '22 14:11

EMC


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 :).

like image 41
Nicky Avatar answered Nov 04 '22 15:11

Nicky


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

like image 1
Tobi Avatar answered Nov 04 '22 16:11

Tobi