OG 圖片 (og-img)

使用 og-img,您可以輕鬆地將動態 Open Graph 圖片新增至您的 Qwik 網站。 這些圖片會在例如您的網站透過社群媒體或通訊軟體分享時顯示。

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 網站的 head 中使用 meta 標籤指向這個 API 端點,即可嵌入 Open Graph 圖像。

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

您也可以透過在路由中匯出 head 物件來動態產生 meta 標籤。

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