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