OG 图片 (og-img)

使用 og-img,您可以轻松地为您的 Qwik 网站添加动态 Open Graph 图片。例如,当您的网站在社交媒体或消息服务上分享时,这些图片会显示。

og-img 是一个框架无关的包,用于使用 Satoriresvg 生成 Open Graph 图片。

要开始使用,请安装 npm 包

npm install og-img

工作原理

要生成图片,您只需通过服务器端点返回一个 ImageResponse。要创建一个,请在您的 Qwik 网站中添加一个新的路由,并在索引文件中导出一个名为 onGet 的函数。为了轻松地定义图片的内容,您可以使用 html 标记的模板字面量。

为了在 Visual Studio Code 中获得标记的模板字面量的正确语法高亮显示,您可以安装 lit-html 扩展。

src/routes/og-image/index.ts
import type { RequestHandler } from '@builder.io/qwik-city';
import { fetchFont, ImageResponse, html } from 'og-img';
 
export const onGet: RequestHandler = async ({ send }) => {
  send(
    new ImageResponse(
      // Use Tailwind CSS or style attribute
      html`
        <div tw="text-4xl text-green-700" style="background-color: tan">
          Hello, world!
        </div>
      `,
      {
        width: 1200,
        height: 600,
        fonts: [
          {
            name: 'Roboto',
            // Use `fs` (Node.js only) or `fetch` to read font file
            data: await fetchFont(
              'https://www.example.com/fonts/roboto-400.ttf'
            ),
            weight: 400,
            style: 'normal',
          },
        ],
      }
    )
  );
};

然后,您需要做的就是在您的 Qwik 网站的头部使用元标记指向此 API 端点,以嵌入 Open Graph 图片。

<head>
  <title>Hello, world!</title>
  <meta property="og:image" content="https://www.example.com/og-image" />
</head>

您也可以通过在路由中导出一个 head 对象来动态生成元标记。

src/routes/index.tsx
import { component$ } from '@builder.io/qwik';
import type { DocumentHead } from '@builder.io/qwik-city';
 
export default component$(() => {
  return <h1>Hello, world!</h1>;
});
 
export const head: DocumentHead = {
  title: 'Hello, world!',
  meta: [
    {
      property: 'og:image',
      content: 'https://www.example.com/og-image',
    },
  ],
};

您可以使用 URL 参数来动态更改 Open Graph 图片的内容。请查看 Valibot 的 Open Graph 图片。您可以在 此处 找到源代码。

贡献者

感谢所有帮助改进这份文档的贡献者!

  • fabian-hiller
  • aendel