【问题标题】:Can I use @vercel/og without React?我可以在没有 React 的情况下使用 @vercel/og 吗?
【发布时间】:2022-12-30 17:40:16
【问题描述】:

我正在尝试在 Vercel 上创建一个 API,它返回根据请求生成的图像。我想为此使用@vercel/og,因为它可以从 HTML 生成图像,而且速度非常快。然而,它似乎需要 React,这对于根本不提供实际 HTML 的东西来说似乎完全没有必要。

我在api/test.ts 中有一个边缘函数:

import { ImageResponse } from '@vercel/og';

export const config = {
    runtime: 'experimental-edge',
};

export default function () {
    return new ImageResponse({
        type: "div",
        props: {
            children: "Hello, World",
            style: {
                backgroundColor: "black",
                color: "white",
                width: "100%",
                height: "100%",
            }
        }
    }, { width: 500, height: 500 });
}

当部署到 Vercel 时,它运行得很好,但是当我使用 vercel dev 时,它给了我这些错误:

Failed to instantiate edge runtime.
Invalid URL: ../vendor/noto-sans-v27-latin-regular.ttf
Error: Failed to complete request to /api/test: Error: socket hang up
node_modules/@vercel/og/dist/og.d.ts:1:35 - error TS2307: Cannot find module 'react' or its corresponding type declarations.

1 import type { ReactElement } from 'react';
                                    ~~~~~~~

node_modules/satori/dist/index.d.ts:1:27 - error TS2307: Cannot find module 'react' or its corresponding type declarations.

1 import { ReactNode } from 'react';
                            ~~~~~~~

node_modules/satori/dist/index.d.ts:14:11 - error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.

14     data: Buffer | ArrayBuffer;
             ~~~~~~


Found 3 errors.

有两个错误说@vercel/og 和satori 找不到 React。有没有解决的办法?我不需要为此做出反应,对吧?

【问题讨论】:

    标签: vercel


    【解决方案1】:

    我通过安装 @types/react 并定义我自己的 JSX 函数并在 .ts 文件中使用它而不使用 JSX 语法来解决与 React 相关的错误以及无法在没有 Next.js 的情况下运行 .tsx 边缘函数。

    function h<T extends React.ElementType<any>>(
      type: T,
      props: React.ComponentPropsWithRef<T>,
      ...children: React.ReactNode[]
    ) {
      return {
        type,
        key: "key" in props ? props.key : null,
        props: {
          ...props,
          children: children && children.length ? children : props.children,
        },
      };
    }
    

    在此之后,您可以在 Vercel 部署预览中运行它。

    但是,在vercel dev本地,我仍然收到以下错误。

    Failed to instantiate edge runtime.
    Invalid URL: ../vendor/noto-sans-v27-latin-regular.ttf
    Error: Failed to complete request to /api/og: Error: socket hang up
    

    我还强制 vercel CLI 在 package.json 中使用更新的 TypeScript 版本和 pnpm.overrides

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-31
      • 2019-01-31
      • 2016-08-11
      • 2021-08-10
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多