Запуск Lighthouse в бессерверной функции Vercel - PullRequest
0 голосов
/ 03 августа 2020

Кто-нибудь пробовал раньше запустить модуль 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 голосов
/ 19 августа 2020

Как следует из ошибки, переменной среды CHROME_PATH не существует. Один из способов решить эту проблему - использовать кукловод. ПРИМЕЧАНИЕ. Если вы используете учетную запись для хобби, существует жесткое ограничение в 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');
  }
};

и ваш пакет. json

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