@vercel/og Pages Plugin 是一个中间件,用于为网页渲染社交图片。它还包含 API 用于创建任意图片。
顾名思义,它由 @vercel/og ↗ 提供支持。此 Plugin 及其底层 Satori ↗ 库由 Vercel 团队创建。
要安装 @vercel/og Pages Plugin,请运行:
npm i @cloudflare/pages-plugin-vercel-ogyarn add @cloudflare/pages-plugin-vercel-ogpnpm add @cloudflare/pages-plugin-vercel-ogbun add @cloudflare/pages-plugin-vercel-ogimport React from "react";
import vercelOGPagesPlugin from "@cloudflare/pages-plugin-vercel-og";
interface Props {
ogTitle: string;
}
export const onRequest = vercelOGPagesPlugin<Props>({
imagePathSuffix: "/social-image.png",
component: ({ ogTitle, pathname }) => {
return <div style={{ display: "flex" }}>{ogTitle}</div>;
},
extractors: {
on: {
'meta[property="og:title"]': (props) => ({
element(element) {
props.ogTitle = element.getAttribute("content");
},
}),
},
},
autoInject: {
openGraph: true,
},
});Plugin 接受一个包含六个属性的对象:
-
imagePathSuffix:生成图片可用的路径后缀。例如,如果在functions/blog/_middleware.ts挂载此 Plugin,将imagePathSuffix设置为/social-image.png并有/blog/hello-world页面,图片将在/blog/hello-world/social-image.png上可用。 -
component:用于渲染图片的 React 组件。默认情况下,React 组件获得等于底层网页路径名(例如/blog/hello-world)的pathname属性,但可以使用extractors选项提供更动态的属性。 -
extractors:可选对象,包含两个可选属性:on和onDocument。这些属性可以设置为接受对象并分别返回HTMLRewriter元素处理器 或文档处理器 的函数。可以修改对象参数以为 React 组件提供附加属性。在上面的示例中,将使用元素处理器从网页提取og:titlemeta 标签,并将其作为ogTitle属性传递给 React 组件。这是创建使用底层网页值的动态图片的主要机制。 -
options:可选对象,直接传递给@vercel/og库 ↗。 -
onError:可选函数,返回Response或Promise<Response>。当向imagePathSuffix发出请求且提供了extractors但底层网页不是有效 HTML 时调用此函数。默认返回404响应。 -
autoInject:可选对象,包含可选属性openGraph。如果设置为true,Plugin 将自动在底层网页上设置og:image、og:image:height和og:image:widthmeta 标签。
使用此 Plugin 的 API 生成任意图片,而不仅作为中间件。
例如,以下代码将生成显示 "Hello, world!" 的图片,可在 /greet 访问。
import React from "react";
import { ImageResponse } from "@cloudflare/pages-plugin-vercel-og/api";
export const onRequest: PagesFunction = async () => {
return new ImageResponse(
<div style={{ display: "flex" }}>Hello, world!</div>,
{
width: 1200,
height: 630,
}
);
};这与底层 @vercel/og 库 ↗ 提供的 API 相同。