dzava / lighthouse
Google Lighthouse项目的接口
v0.2.0
2022-03-15 18:48 UTC
Requires
- php: >=7.4
- ext-json: *
- symfony/process: ^4.0|^5.0|^6.0
Requires (Dev)
- dms/phpunit-arraysubset-asserts: ^0.2.0
- phpunit/phpunit: ^8.4|^9.0
This package is auto-updated.
Last update: 2024-09-21 08:24:30 UTC
README
此包为Google Lighthouse提供了一个PHP接口。
安装
您可以通过composer安装此包:composer require dzava/lighthouse
安装Lighthouse:yarn add lighthouse
。最后测试了Lighthouse v8.5.1版本。
使用
以下是一个示例,它将执行默认的Lighthouse审计并将结果存储在report.json
文件中(您可以使用Lighthouse Viewer打开报告)
use Dzava\Lighthouse\Lighthouse; (new Lighthouse()) ->setOutput('report.json') ->accessibility() ->bestPractices() ->performance() ->pwa() ->seo() ->audit('http://example.com');
输出
setOutput
方法接受第二个参数,可以用来指定格式(json、html)。如果缺少格式参数,则将使用文件扩展名来决定输出格式。如果文件扩展名未指定接受的格式,则默认使用json。
通过传递数组作为第二个参数,您可以输出json和html报告。对于示例,以下代码将创建两个报告example.report.html
和example.report.json
。
use Dzava\Lighthouse\Lighthouse; (new Lighthouse()) ->setOutput('example', ['html', 'json']) ->performance() ->audit('http://example.com');
使用自定义配置
您可以使用withConfig
方法提供自己的配置文件。
use Dzava\Lighthouse\Lighthouse; (new Lighthouse()) ->withConfig('./my-config.js') ->audit('http://example.com');
您还可以将包含您的配置的PHP数组传递给withConfig
方法。
use Dzava\Lighthouse\Lighthouse; (new Lighthouse()) ->withConfig([ 'extends' => 'lighthouse:default', 'settings' => [ 'onlyCategories' => ['accessibility'], ], ]) ->audit('http://example.com');
注意:为了使用数组来指定配置选项,PHP需要能够创建和移动临时文件。
有关配置选项的详细信息,请在此处查看。
自定义node和Lighthouse路径
如果您需要手动设置这些路径,可以通过调用setNodeBinary
和setLighthousePath
方法来完成。
use Dzava\Lighthouse\Lighthouse; (new Lighthouse()) ->setNodeBinary('/usr/bin/node') ->setLighthousePath('./node_modules/lighthouse/lighthouse-cli/index.js') ->audit('http://example.com');
向Chrome传递标志
使用setChromeFlags
方法向Chrome实例传递任何标志。
use Dzava\Lighthouse\Lighthouse; (new Lighthouse()) // these are the default flags used ->setChromeFlags(['--headless', '--disable-gpu', '--no-sandbox']) ->audit('http://example.com');
故障排除
'url'审计失败
使用以下片段来检查审计失败的原因。
require "./vendor/autoload.php"; use Dzava\Lighthouse\Exceptions\AuditFailedException; use Dzava\Lighthouse\Lighthouse; try { (new Lighthouse()) ->performance() ->audit('http://example.com'); } catch(AuditFailedException $e) { echo $e->getOutput(); }