在Vercel无服务器功能中运行Lighthouse

时间:2020-08-03 17:41:11

标签: javascript google-chrome vercel

以前有没有人试图在无服务器功能内运行lighthouse npm模块? 我正在尝试在无服务器Vercel功能中运行此代码,但出现以下错误。我了解没有CHROME_PATH环境变量,但是知道如何解决这个问题吗?

const lighthouse = require("lighthouse");
const chromeLauncher = require("chrome-launcher");
const { generateLighthouseStats } = require("../src/generateLighthouseStats");

module.exports = async (req, res) => {
  let { website } = req.query;

  const categories = "performance,seo,accessibility,pwa,best-practices";
  const categoriesList = categories.split(",").filter(Boolean);

  const chrome = await chromeLauncher.launch({
    chromeFlags: ["--headless"]
  });

  const options = {
    logLevel: "info",
    onlyCategories: categoriesList,
    port: chrome.port
  };

  const runnerResult = await lighthouse(website, options);
  const response = {};

  if (categoriesList.includes("performance")) {
    const performance = runnerResult.lhr.categories.performance.score * 100;
    response.performance = performance;
  }
  if (categoriesList.includes("seo")) {
    const seo = runnerResult.lhr.categories.seo.score * 100;
    response.seo = seo;
  }
  if (categoriesList.includes("accessibility")) {
    const accessibility = runnerResult.lhr.categories.accessibility.score * 100;
    response.accessibility = accessibility;
  }
  if (categoriesList.includes("pwa")) {
    const pwa = runnerResult.lhr.categories.pwa.score * 100;
    response.pwa = pwa;
  }
  if (categoriesList.includes("best-practices")) {
    const bestPractices = runnerResult.lhr.categories["best-practices"].score * 100;
    response.bestPractices = bestPractices;
  }

  await chrome.kill();

  res.setHeader("Content-Type", "image/svg+xml");
  res.setHeader("Cache-Control", `public, max-age=1600`);
  res.send(
    generateLighthouseStats({
        performance: response.performance,
        accessibility: response.accessibility,
        seo: response.seo,
        pwa: response.pwa,
        bestPractices: response.bestPractices
      },
      runnerResult.lhr.finalUrl
    )
  );
};


我遇到以下错误:

2020-08-03T11:01:28.936Z    6334e987-a67a-4c9e-9061-3cf3a7f79318    ERROR   Unhandled Promise Rejection 
{
  "errorType": "Runtime.UnhandledPromiseRejection",
  "errorMessage": "Error: The environment variable CHROME_PATH must be set to executable of a build of Chromium version 54.0 or later.",
  "reason": {
    "errorType": "Error",
    "errorMessage": "The environment variable CHROME_PATH must be set to executable of a build of Chromium version 54.0 or later.",
    "code": "ERR_LAUNCHER_PATH_NOT_SET",
    "message": "The environment variable CHROME_PATH must be set to executable of a build of Chromium version 54.0 or later.",
    "stack": [
      "Error: ",
      "    at new LauncherError (/var/task/node_modules/chrome-launcher/src/utils.ts:31:18)",
      "    at new ChromePathNotSetError (/var/task/node_modules/chrome-launcher/dist/utils.js:44:9)",
      "    at Object.linux (/var/task/node_modules/chrome-launcher/src/chrome-finder.ts:153:11)",
      "    at Function.getFirstInstallation (/var/task/node_modules/chrome-launcher/src/chrome-launcher.ts:183:61)",
      "    at Launcher.<anonymous> (/var/task/node_modules/chrome-launcher/src/chrome-launcher.ts:229:37)",
      "    at Generator.next (<anonymous>)",
      "    at /var/task/node_modules/chrome-launcher/dist/chrome-launcher.js:13:71",
      "    at new Promise (<anonymous>)",
      "    at __awaiter (/var/task/node_modules/chrome-launcher/dist/chrome-launcher.js:9:12)",
      "    at Launcher.launch (/var/task/node_modules/chrome-launcher/dist/chrome-launcher.js:156:16)"
    ]
  },
  "promise": {},
  "stack": [
    "Runtime.UnhandledPromiseRejection: Error: The environment variable CHROME_PATH must be set to executable of a build of Chromium version 54.0 or later.",
    "    at process.<anonymous> (/var/runtime/index.js:35:15)",
    "    at process.emit (events.js:322:22)",
    "    at process.emit (/var/task/__sourcemap_support.js:2561:21)",
    "    at processPromiseRejections (internal/process/promises.js:209:33)",
    "    at processTicksAndRejections (internal/process/task_queues.js:98:32)"
  ]
}
Unknown application error occurred

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

如错误所示,没有CHROME_PATH环境变量。解决此问题的一种方法是使用操纵up。注意:如果您使用的是业余帐户,则硬限制为10秒,并且在该时间范围内可能无法完成灯塔报告。

无论如何,如果有帮助,这里是代码

import puppeteer from 'puppeteer-core';
import lighthouse from 'lighthouse';
import { URL } from 'url';

async function getOptions() {
  const options = {
    args: chrome.args,
    executablePath: await chrome.executablePath,
    headless: chrome.headless,
  };
  return options;
}

async function getResult(url) {
  const options = await getOptions();
  const browser = await puppeteer.launch(options);
  const { port } = new URL(browser.wsEndpoint());
  const result = await lighthouse(url, {
    port,
    output: 'html',
    logLevel: 'error',
  });
  await browser.close();
  return result;
}

module.exports = async (req, res) => {
  const urlToBeAudited = 'https://example.com'
  const result = await getResult(urlToBeAudited);
  if (req && result && result.lhr && result.lhr.categories) {
    res.end('Audit done.');
  } else {
    res.end('result is empty');
  }
};

和您的package.json

  "dependencies": {
    "chrome-aws-lambda": "^5.2.1",
    "lighthouse": "^6.2.0",
    "puppeteer-core": "^5.2.1"
  }