Performance audits with GatsbyJS and Lighthouse
2 minutes read
GatsbyJS is a great tool for building static sites. What I like most is how it ties NodeJS, ReactJS and GraphQL together, and the commands it gives you on top of them.
On a recent GatsbyJS project I needed performance audits in the continuous delivery (CD) and continuous integration (CI) pipelines. Lighthouse is the best tool I know for this.
Audits give more accurate results on a production build, so you need one built and running on a server. GatsbyJS can do both locally with gatsby build and gatsby serve.
I usually combine them in the npm scripts in package.json:
...
"scripts": {
"develop": "gatsby develop",
"build": "gatsby build",
"preview": "gatsby build && gatsby serve"
}
...
Run npm run preview and the production site is served at http://localhost:9000. From there you can run an audit from the Audit tab in Chrome DevTools and get a report.
The GatsbyJS docs have a good guide on this.
To run it in a CI/CD pipeline you need the lighthouse command line tool, which you can install as a node module.
npm install -D lighthouse
or
yarn add -D lighthouse
Then add these to the npm scripts in package.json:
...
"scripts": {
...
"preview:start": "(gatsby build && (gatsby serve &))",
"preview:stop": "lsof -i tcp:9000 | awk '{print $2}' | grep \"[0-9]\" | xargs kill -9",
"audit": "lighthouse http://localhost:9000",
"perf:audit": "npm run preview:start ; (npm run audit -- --view && npm run preview:stop)"
}
...
What each one does:
auditrunslighthouseagainsthttp://localhost:9000, the port GatsbyJS serves on.preview:startis likepreview, except GatsbyJS serves the site in the background so the next commands can run.preview:stopkills the background GatsbyJS server, assuming it's on port 9000.perf:auditchains them: build, serve in the background, run the audit, open the report in the browser, then kill the server.
The
--viewflag opens the report in the browser once it's ready.
Gotcha
GatsbyJS tries port 9000 first. If something else is using it, it may offer another port, usually the next one up, like 9001. Then lighthouse can fail, because port 9000 isn't serving the GatsbyJS site.
Using it in CI
lighthouse can write its report as JSON among other formats, so CI tools can read and check it. With a performance budget in place, the CI build fails when the site falls below the minimum you set. That's what we're working towards at Rated People.