首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Vercel Serverless函数中运行灯塔

在Vercel Serverless函数中运行灯塔
EN

Stack Overflow用户
提问于 2020-08-04 01:41:11
回答 1查看 629关注 0票数 0

以前有人尝试过在无服务器函数中运行灯塔npm模块吗?我试图在一个vercel无服务器函数中运行这段代码,但我得到了以下错误。我知道没有CHROME_PATH环境变量,但是你知道我该如何解决这个问题吗?

代码语言:javascript
运行
复制
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
    )
  );
};

我收到以下错误:

代码语言:javascript
运行
复制
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

任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2020-08-19 11:51:06

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

无论如何,如果有帮助,下面是代码

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
  "dependencies": {
    "chrome-aws-lambda": "^5.2.1",
    "lighthouse": "^6.2.0",
    "puppeteer-core": "^5.2.1"
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63234392

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档