LoginSignup
2
4

More than 5 years have passed since last update.

Lighthouseを自動化する 〜その2〜

Last updated at Posted at 2018-10-07

Lighthouse大事

LighthouseはGoogleが出しているWebサイトのパフォーマンス測定ツール。
今後はMFIが進んでいくこともあり、Lighthouseの数値を日頃からチェックしておくことは大事。
Webサイトに改修を加えた結果、スコアが落ちてSEOの評価が下がってしまったら目も当てられない。

screenshots_001.png

Lighthouseは面倒

Lighthouseの実行はChrome拡張機能やChromeのデベロッパーツールから実行することができる。
けど、毎回対象のページをブラウザで開いてツールを実行するのは結構面倒。
あと、スコアの共有も面倒。

なので今回は、以下の3つの処理をJavaScript上から自動で行う。
1. スプレッドシートから対象のURLを取得
2. Lighthouseのスコアを取得(今回)
3. Slackへの通知まで

Lighthouseのスコアを取得

Lighthouse CLIのインストール

LighthouseはCLIが公開されているのでインストールする。

npm i -g lighthouse

JavaScriptでLighthouse実行

CLIを呼び出すため、execSync()を使用している。
※execSyncのプロセスがkillされないときがあるので、対応方法知ってる方がいたら教えてほしい…

const execSync = require('child_process').execSync;

exports.getLighthouseScore = (url) => {
  return new Promise((resolve, reject) => {
    try {
      console.log(`${url}`);

      // Lighthouse CLIを実行
      const result = execSync(`lighthouse "${url}" --output json --quiet`, {timeout: 60000}).toString();
      const stats = JSON.parse(result);

      const scoreMap = Object.entries(stats.categories).reduce((acc, [key, val]) => {
        return Object.assign({}, acc, {[val.title]: val.score ? parseInt(val.score * 100) : 0 });
      }, {});

      resolve(scoreMap);
    } catch(e) {
      reject({});
      execSync
    } 
  });
}
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4