


How to use NodeJS + Lighthouse + Gulp to build an automated website performance testing tool
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:
Open Chrome browser
Press F12
-
Open the audits tab in the pop-up window
Click Perform an audit...check all
Run audit
- Install Node
- Install Lighthouse
npm install -g lighthouse
- run in the command line
lighthouse
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:
npm i lighthouse --save-dev npm i chrome-launcher --save-dev npm i fs-extra --save-dev npm i gulp --save-devConfigurationCreate 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' }If readers need to know more detailed configuration options, please refer to:
- Lighthouse Most of this article is about the command line, and command line parameters can also be used Node
- throttlingThis article is about network simulation
- Default Config Specific default configuration parameters
- Web Page Test simulates different network speeds
- Emulation simulates different devices
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');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); } }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); } }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"); } }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'); }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(); }
下面, 我们可以正式开始写一个 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
万事大吉。
附上汇总界面的模板源码:
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>
Case No. | First Meaningful Paint | Link To Details |
---|
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
jQuery+AJAX+PHP+MySQL开发搜索无跳转无刷新的功能
关于vue中extend,mixins,extends,components,install的操作
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!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool