Home > Web Front-end > JS Tutorial > body text

How to use NodeJS + Lighthouse + Gulp to build an automated website performance testing tool

不言
Release: 2018-07-13 16:46:11
Original
2685 people have browsed it

This article mainly introduces how to use NodeJS Lighthouse Gulp to build automated website performance testing tools. It has a certain reference value. Now I share it with you. Friends in need can refer to it.

Assuming you still I don’t know what Lighthouse is

Lighthouse is an open source tool owned by Google that can automatically detect website quality. It has a friendly interface, simple operation, diverse usage methods, and comprehensive perspectives. You can use it to test any web page. Normally Users, QA, and developers can all get started quickly.

Startup posture

Difficulty level 1

There are many ways to use Lighthouse. The simplest one is to use Chrome's developer tools. The steps are as follows:

  1. Open Chrome browser

  2. Press F12

  3. Open the audits tab in the pop-up window

  4. Click Perform an audit...check all

  5. Run audit

##Difficulty level 2

You can also use the command line.

  1. Install Node

  2. Install Lighthouse

    npm install -g lighthouse

  3. run in the command line

    lighthouse

The above two usage methods are not the focus of this article. If you want to learn more, you can refer to Run Lighthouse in DevTools

Difficulty level 3

Since I am learning NodeJS recently, I decided to use Node 8 Gulp to run lighthouse. In order to improve the accuracy of the results, I ran lighthouse 10 times for each task, and We only care about the

first-meaningful-paint milliseconds in the result indicator, and finally take the average of 10 times. For the sake of visualization and readability, the final results are displayed in the form of a web page, and users can view it on the web page. You can also see the average number of milliseconds to first-meaningful-paint after each execution of Lighthouse. If the user is interested in the details of a certain execution, he can click on the link to view it. The final result looks like this:

How to use NodeJS + Lighthouse + Gulp to build an automated website performance testing tool

How to use NodeJS + Lighthouse + Gulp to build an automated website performance testing tool

Environment setup

Install Node 8

Install dependencies Package

npm i lighthouse --save-dev
npm i chrome-launcher --save-dev
npm i fs-extra --save-dev
npm i gulp --save-dev
Copy after login
Configuration

Create the Lighthouse configuration file

lighthouse-config.js in the project root directory. Here we all use the default configuration. To use the default configuration, you need to configure The file declares extends: 'lighthouse:default'.

module.exports = {
    extends: 'lighthouse:default'
}
Copy after login
If readers need to know more detailed configuration options, please refer to:

  1. Lighthouse Most of this article is about the command line, and command line parameters can also be used Node

  2. throttlingThis article is about network simulation

  3. Default Config Specific default configuration parameters

  4. Web Page Test simulates different network speeds

  5. Emulation simulates different devices

Coding

In the project root directory Create

gulpfile.js, first introduce all dependent tools:

const gulp = require('gulp');
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const printer = require('lighthouse/lighthouse-cli/printer');
const Reporter = require('lighthouse/lighthouse-core/report/report-generator');
const fs = require('fs-extra');
const config = require('.lighthouse-config.js');
Copy after login
Before starting to use lighthouse, first create a method to write files, which will be used to finally generate a customized report file :

async function write(file, report) {
    try {
        await fs.outputFile(file, report);
    } catch (Error e) {
        console.log("error while writing report ", e);
    }
}
Copy after login
Before calling Lighthouse, we need to first start a Chrome instance and provide the port number to Lighthouse.

--headless means not opening the browser window.

async function launchChrome() {
    let chrome;
    try {
        chrome =  await chromeLauncher.launch({
          chromeFlags: [
            "--disable-gpu",
            "--no-sandbox",
            "--headless"
          ],
          enableExtensions: true,
          logLevel: "error"
        });
        console.log(chrome.port)
        return {
            port: chrome.port,
            chromeFlags: [
                "--headless"
            ],
            logLevel: "error"
         }
    } catch (e) {
        console.log("Error while launching Chrome ", e);
    }
}
Copy after login
After the Chrome instance is started, we can call Lighthouse. When calling, we must provide the website that needs to be performance tested, parameters, and the configuration created previously. The parameters include Chrome startup port, startup method (whether headless and other information).

async function lighthouseRunner(opt) {
    try {
        return await lighthouse("https://www.baidu.com", opt, config);
    } catch (e) {
        console.log("Error while running lighthouse");
    }
}
Copy after login
The return result of Lighthouse is a json object containing performance test results, final version of configuration parameters, indicator grouping and other information. Readers can refer to Understanding Results for a deeper understanding.

Since we need to use the official Lighthouse template to generate the report, we call the official method. Note that the first parameter is passed in
result.lhr, and the second parameter is declared to generate an html report (you can also Generate reports in csv and other formats).

function genReport(result) {
    return Reporter.generateReport(result.lhr, 'html');
}
Copy after login
Next we write a function that strings together the above methods. First, start a Chrome instance, then pass some parameters of the Chrome instance to Lighthouse, use the results run by lighthouse to generate a report, and write Enter the html file. The html file should have a timestamp and execution sequence as a unique identifier. The

start method returns first-meaningful-paint in the result (this is the indicator we are most concerned about. Readers can replace it according to their own needs. For specific indicators, please refer to Lighthouse).

async function run(timestamp, num) {
    let chromeOpt = await launchChrome();
    let result = await lighthouseRunner(chromeOpt);
    let report = genReport(result);
    await printer.write(report, 'html', `./cases/lighthouse-report@${timestamp}-${num}.html`);
    return result.lhr.audits['first-meaningful-paint'].rawValue;
    await chrome.kill();
}
Copy after login

下面, 我们可以正式开始写一个 gulp task 啦,首先获得当前时间戳,用于最终生成的报告命名,然后声明一个数组,用于记录每次跑 Lighthouse 生成的 first-meaningful-paint 毫秒数,然后跑10次 Lighthouse, 使用提前创建的模板文件,根据这10的结果,生成一个汇总报告,这里,笔者使用了Lighthouse对外暴露的工具函数进行字符串的替换。

gulp.task('start', async function() {
  let timestamp = Date.now();
  let spent = [];
  for(let i=0; i<p>最后的最后, 执行:</p><pre class="brush:php;toolbar:false">gulp start
Copy after login

万事大吉。
附上汇总界面的模板源码:

nbsp;html>


  <meta>
  <meta>
  <title>Lighthouse Summary Report</title>
  <style>
    body {
      font-family: sans-serif;
    }
    table {
      margin: auto;
    }
    tr {
      border: 1px solid grey;
    }
    h1 {
       text-align: center;
       margin: 30px auto 50px auto
    }
  </style>


Copy after login
  

Performance Summary Report

                          
      Case No.            First Meaningful Paint            Link To Details     
<script> let timespent = %%TIME_SPENT%%; let timestamp = %%TIMESTAMP%%; let tableBody = document.getElementById("tableBody"); let content = &#39;&#39;; for(let i=0; i < timespent.length; i++) { content += `<tr style="border: 1px solid grey"> <td> ${i+1} <td> ${timespent[i]} <td> <a href="../../cases/lighthouse-report@${timestamp}-${i}.html">View Details ` } let total = timespent.reduce((i, j) => { return i + j; }) let count = timespent.filter(function(i) { return i}).length content += `<tr> <td> AVG <td> ${total / count} ` tableBody.innerHTML = content; </script>

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

 jQuery+AJAX+PHP+MySQL开发搜索无跳转无刷新的功能

关于vue中extend,mixins,extends,components,install的操作

Vue+Mock.js如何搭建前端独立开发环境

The above is the detailed content of How to use NodeJS + Lighthouse + Gulp to build an automated website performance testing tool. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template