Lighthouse 是谷歌 Web 开发“四件套”之一。html
经常使用的性能评测工具 PageSpeed 内部就是用 Lighthouse 实现的。前端
本文将说明如何安装使用 Lighthouse Github App,借助 Travis CI,把 Lighthouse 引入开源项目的 Pull Reuqest 工做流中,达到性能分析自动化的效果。node
本文假设读者对 Travis CI 有必定的了解 ,若是没有,能够查看 Travis CI 教程。git
Lighthouse 是针对静态页面进行分析的,所以分析前须要先构建前端应用,生成 html。github
假设前端应用构建命令为 yarn build
, 生成的静态文件目录为 static
,只在 master
分支触发构建。web
则 Travis CI 参考配置以下,关键点是:chrome
运行 lhci npm
branches: only: - master language: node_js node_js: - lts/* before_install: - yarn global add @lhci/cli install: - yarn - yarn build script: - lhci autorun --upload.target=temporary-public-storage --collect.staticDistDir=./static addons: chrome: stable cache: yarn
复制上面的代码,放到 .travis.yml 里,并提交到仓库中。性能优化
点击:https://github.com/apps/lighthouse-ci/installations/newbash
受权后,保存 token
进入 Travis CI,添加环境变量:LHCI_GITHUB_APP_TOKEN,值为上面保存的 token
向 master 提交 PR,便可
分析 Travis CI 的日志
能够得知,lighthouse 会启动内置一个随机端口的 web server,经过配置文件里指定的静态文件夹,访问到 index.html。测试了三次后,把诊断结果上传到临时的云存储空间中。
假设如今想测试的不是 index.html,或不止测试一个页面,又该如何操做?
能够经过 collect.url=http://localhost/xxx
来配置,示例以下:
lhci autorun --upload.target=temporary-public-storage --collect.staticDistDir=./ --collect.url=http://localhost/static --collect.url=http://localhost/another-page
注意此时不须要指定端口号
看看实际项目 FEMessage/create-nuxt-app 是怎么作的。
create-nuxt-app 在 CI 时共会生成三个目录,每个目录构建后都是一个spa,它们经过同一个 index.html 做为统一入口。也即,咱们要评估的不是做为统一入口的 index.html,而是三个 spa 的首页。
另外,咱们只会在 dev 分支进行 lhci 的性能评估,master 是用于发布npm、生成源码zip包的。
下面是 .travis.yml
branches: only: - master - dev language: node_js node_js: - lts/* install: - yarn --frozen-lockfile script: - yarn test - yarn generate # https://stackoverflow.com/questions/37544306/travis-different-script-for-different-branch - test "$TRAVIS_BRANCH" = "dev" && yarn build && ./lhci.sh || echo skip - test "$TRAVIS_BRANCH" = "master" && yarn zip || echo skip addons: chrome: stable deploy: - provider: script skip_cleanup: true script: npx semantic-release on: branch: master after_script: - ./notify.sh
lhci.sh
#!/bin/sh yarn global add @lhci/cli lhci autorun --upload.target=temporary-public-storage --collect.staticDistDir=./dist --collect.url=http://localhost/nuxt-element-dashboard --collect.url=http://localhost/nuxt-multiple-spa --collect.url=http://localhost/nuxt-vant
notify.sh
#!/bin/sh if [ "$TRAVIS_BRANCH" != "master" ] then echo "do not notify cause not on master branch" exit 0 fi if [ "$TRAVIS_TEST_RESULT" != "0" ] then echo "build not success, bye" exit 1 fi GREN_GITHUB_TOKEN=$GITHUB_TOKEN yarn release
Lighthouse 是开源的,也有不少衍生的工具,初次使用,可能学习曲线稍微有些陡峭,建议先从 Lighthouse Github App 入手,先在开源项目中尝试,有了成功经验后,后续再用相应的命令行工具,引入内部项目中。
有同窗可能会问,这跟直接使用使用 PageSpeed 进行页面分析有什么不一样呢?
这个问题问题得好。能够这样想,使用 PageSpeed 去分析的时候,都是在项目里程碑末期。而使用工具,能够把性能分析引入到研发流程中间,能够自动化,并提早发现问题。更关键的是,这利于加强团队的性能优化意识,为建立性能文化打下基础。