博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何确保您的Progressive Web App保持其Lighthouse审核分数
阅读量:2518 次
发布时间:2019-05-11

本文共 8992 字,大约阅读时间需要 29 分钟。

by Ondrej Chrastina

通过Ondrej Chrastina

如何确保您的Progressive Web App保持其Lighthouse审核分数 (How to make sure your Progressive Web App keeps its Lighthouse audit score)

I bet most of you have implemented a web application before. Some of you may even have created a (PWA) that can act as a native app installed in a device. You’ve maybe followed to make your app fully compliant with prescribed PWA rules and conventions via the Lighthouse audit tool.

我敢打赌,你们大多数人以前已经实现了Web应用程序。 你们中的某些人甚至可能已经创建了一个 (PWA),可以用作安装在设备中的本机应用程序。 您可能已经遵循了 ,可以通过Lighthouse审核工具使您的应用完全符合规定的PWA规则和约定。

Now, wouldn’t it be nice to run the audit every time some of your colleagues updates the code-base? Accidents happen, and even if you and your colleagues strive for a 100% compliant PWA, it is always great to get early warnings, immediately after each build.

现在,每次您的一些同事更新代码库时进行审核不是很好吗? 有时会发生事故,即使您和您的同事努力实现100%符合PWA的要求,每次构建后立即获得预警也总是很棒的。

In the following article, I’ll describe how to check the compliance automatically by embedding the PWA audit into your continuous integration pipeline.

在下面的文章中,我将介绍如何通过将 PWA审核嵌入到您的持续集成管道中来自动检查合规性。

I’ll start exactly where I left off in (that is, working with the sample travel application that lists interesting places to visit). The app stores its data in the and it meets all the . Following each implementation step, I will provide a GitHub link to the code state to allow you to try the changes step by step, without the need to write the code on your own.

我将从刚停下来的地方开始(也就是使用示例旅行应用程序,其中列出了有趣的景点)。 该应用程序将其数据存储在 ,并且满足所有 。 在每个实现步骤之后,我将提供一个指向代码状态的GitHub链接,使您可以逐步尝试所做的更改,而无需自己编写代码。

I will use the . Although Lighthouse could be used directly from the command line, its programmatic form is better as it properly reports success, failure, and the audit score.

我将使用 。 虽然Lighthouse可以直接从命令行使用,但是它的程序形式更好,因为它可以正确报告成功,失败和审核分数。

I’ll do basically two things. First, I’ll show how to use the package the from command line to emit a JSON string with the audit results into my console window. Then I will show how to use the npm package in a continuous integration pipeline.

我基本上会做两件事。 首先,我将展示如何使用from命令行软件包在控制台窗口中发出带有审计结果的JSON字符串。 然后,我将展示如何在连续集成管道中使用npm软件包。

如何从命令行使用Lighthouse软件包 (How to use the Lighthouse package from the command line)

Let’s start by installing Lighthouse as a development dependency to the project.

让我们首先安装Lighthouse作为项目的开发依赖项。

npm install --save-dev lighthouse

For deployment, I am using service. You just have to register on its site and install the CLI tools (in the following example globally). Then, you’re able to deploy the folder into a *.surge.sh sub-domain.

对于部署,我正在使用服务。 您只需要在其站点上注册并安装CLI工具(在以下示例中为全局)。 然后,您可以将文件夹部署到* .surge.sh子域中。

npm install -g surge
  • surge /dist your-own-subdomain.surge.sh for example deploy the “dist” folder to the specified URL. This requires you to either log in or with the login and token.

    例如,将surge /dist your-own-subdomain.surge.sh部署到指定的URL。 这要求您登录或使用登录名和令牌 。

In your package.json file, define a public URL where your app will be deployed, like so:

package.json文件中,定义将在其中部署应用程序的公共URL,如下所示:

{..."config": {   "deployUrl": "https://your-own-subdomain.surge.sh"},...}

Lighthouse will be configured to perform the audit against this URL. But, in order to do that, it needs to wait a few seconds before the app (or a new version of it) becomes publicly accessible.

Lighthouse将配置为针对此URL执行审核。 但是,为此,它需要等待几秒钟,然后该应用程序(或其新版本)才能公开访问。

Surge sometimes takes its time when publishing your app. Therefore, you should use the package (or something similar) to wait for two seconds before performing the audit. Let’s get through it. Install the package to the development dependencies.

发布应用程序时,Surge有时会花费一些时间。 因此,在执行审核之前,应使用程序包(或类似的程序)等待两秒钟。 让我们来解决它。 将软件包安装到开发依赖项。

npm install --save-dev npm-delay

Once you’re done with installing, define the script command for deployment using Surge to your URL. Then, define the “lighthouse” script command that will build the app in production mode into the dist folder, use the “deploy” command, wait for two seconds (to make sure that last version of app is publicly accessible), and then run the PWA audit against the application’s URL.

安装完成后,请使用Surge到URL定义用于部署的脚本命令。 然后,定义“灯塔”脚本命令,将生产模式下的应用程序构建到dist文件夹中,使用“部署”命令,等待两秒钟(以确保可以公开访问该应用程序的最新版本),然后运行针对应用程序的URL进行PWA审核。

{..."scripts": {    ...    "deploy": "surge dist %npm_package_config_deployUrl%",    "lighthouse": "npm run build && npm run deploy && npm-delay 2000 && lighthouse --chrome-flags=\"--headless\" --quiet --output=json %npm_package_config_deployUrl%",    ...  }...}

Alright, let’s run the command:

好吧,让我们运行命令:

npm run lighthouse

In the console, you’ll see a huge JSON string with the audit result. What you want to inspect is the reportingCategories property, its inner part (report) named “Progressive Web App” with its property called score.

在控制台中,您将看到一个巨大的JSON字符串以及审核结果。 您要检查的是reportingCategories属性,其内部(报告)名为“ Progressive Web App”,其属性称为score

{  ...  "reportCategories": [    ....    {      "name": "Progressive Web App",      ...      "id": "pwa",      "score": 100    }  ...  }

将Lighthouse检查添加到持续集成管道中 (Add the Lighthouse check to the Continuous Integration pipeline)

To plug the PWA audit into the CI pipeline, we can use the of using Lighthouse. First of all, you’ll want to define the JavaScript script that will check the score of you PWA.

要将PWA审核插入CI管道,我们可以使用使用Lighthouse的 。 首先,您需要定义JavaScript脚本,该脚本将检查您的PWA得分。

The script uses the URL defined in the package.json file. In that script, there is a function used to run the and perform the Lighthouse audit on it. After the audit is finished, the script will wait for two seconds to be sure that your application is deployed and accessible. Finally, the script selects the value from the audit result JSON string and checks whether it meets the defined score level — 100 in this case. Otherwise it returns the exit code 1, which will in turn cause the build to fail.

该脚本使用package.json文件中定义的URL。 在该脚本中,有一个函数用于运行并对其执行Lighthouse审核。 审核完成后,脚本将等待两秒钟,以确保您的应用程序已部署且可访问。 最后,脚本从审计结果JSON字符串中选择值,并检查其是否满足定义的分数级别(在这种情况下为100)。 否则,它将返回退出代码1,这又将导致构建失败。

const lighthouse = require('lighthouse');const chromeLauncher = require('chrome-launcher');const appConfig = require('./package');
const opts = {    chromeFlags: ['--headless']};
function launchChromeAndRunLighthouse(url, opts, config = null) {    return chromeLauncher.launch({ chromeFlags: opts.chromeFlags }).then(chrome => {        opts.port = chrome.port;        return lighthouse(url, opts, config).then(results => {            delete results.artifacts;            return chrome.kill().then(() => results);        });    });}
launchChromeAndRunLighthouse(appConfig.config.deployUrl, opts).then(results => {    setTimeout(() => {      if (results.reportCategories.filter((item) => item.id === "pwa").length) {        const score = results.reportCategories.filter((item) => item.id === "pwa")[0].score        if (score >= 100) {            console.info(`PWA score is 100.`);            process.exit(0);        }        console.error(`Score is lower than 100. It is ${score}`);        process.exit(1);    }    console.error(`No PWA score provided by lighthouse.`);    process.exit(1);    }, 2000);    });

Let’s define the new script in the package.json file.

让我们在package.json文件中定义新脚本。

{...    "scripts": {    ...    "check-pwa-score": "node checkLighthouse.js"    ...    }...}

Finally trigger Travis build and publish out a 100% compliant PWA!

最终触发Travis构建并发布100%兼容的PWA

I am using a yaml file for Travis configuration. Basically, you just sign in to by your GitHub account, turn on the CI to repository in the Travis UI, and then you just commit the file .travis.yml to the root of your repository.

我正在使用Yaml文件进行Travis配置。 基本上,您只需使用GitHub帐户登录 ,在Travis UI中打开配置项的CI,然后将.travis.yml文件.travis.yml到存储库的根目录。

sudo: requireddist: trustylanguage: node_jsnode_js:- "stable"before_script:- npm installbefore_deploy:- npm run builddeploy:  provider: surge  project: ./dist/  domain: https://kentico-cloud-sample-angular-pwa-app.surge.sh   skip_cleanup: trueafter_deploy:- npm run check-pwa-score

As you can see at the bottom, there is an after-deploy action that checks the PWA audit score.

如您在底部看到的,有一个部署后操作,用于检查PWA审核分数。

Voila! Your build pipeline now automatically checks the PWA audit score.

瞧! 现在,您的构建管道会自动检查PWA审核分数。

From now on, should any of your colleagues hurt the compliance of your PWA app, they will immediately be warned by Travis.

从现在开始,如果您的任何同事损害了您的PWA应用程序的合规性,Travis将立即警告他们。

最后的话 (Final words)

Good job! If you’ve followed the steps, you’ve successfully added the Lighthouse npm package to get the JSON string with the results to the console.

做得好! 如果执行了这些步骤,那么您已经成功添加了Lighthouse npm包,以将带有结果的JSON字符串添加到控制台。

You’ve also set things up to automatically publish your app, wait two seconds, and use the Lighthouse functionality in the Headless Chrome to check for your score in a Travis CI pipeline.

您还设置了自动发布应用程序的功能,等待两秒钟,然后使用Headless Chrome中的Lighthouse功能检查Travis CI管道中的分数。

Now, you no longer have to lose sleep over your precious app!

现在,您不再需要为珍贵的应用程序而沉迷!

翻译自:

转载地址:http://nygwd.baihongyu.com/

你可能感兴趣的文章
BZOJ 1600: [Usaco2008 Oct]建造栅栏( dp )
查看>>
nginx 高并发配置参数(转载)
查看>>
洛谷 CF937A Olympiad
查看>>
Codeforces Round #445 C. Petya and Catacombs【思维/题意】
查看>>
用MATLAB同时作多幅图
查看>>
python中map的排序以及取出map中取最大最小值
查看>>
ROR 第一章 从零到部署--第一个程序
查看>>
<form>标签
查看>>
vue去掉地址栏# 方法
查看>>
Lambda03 方法引用、类型判断、变量引用
查看>>
was集群下基于接口分布式架构和开发经验谈
查看>>
MySQL学习——MySQL数据库概述与基础
查看>>
ES索引模板
查看>>
HDU2112 HDU Today 最短路+字符串哈希
查看>>
JPanel重绘
查看>>
图片放大器——wpf
查看>>
SCALA STEP BY STEP
查看>>
cocos2d-x学习笔记
查看>>
MySql中的变量定义
查看>>
Ruby数组的操作
查看>>