OG images

自动创建 Open Graph 图像的插件

配置参数

extensions string[]

The list of extensions this plugin applies to

Default:
[ ".html" ]
includes string

Custom includes path to load the layout

Default:
site.options.includes
cache string boolean

The cache folder

Default:
true
satori object

The options for Satori to generate the SVG image.

See https://github.com/vercel/satori

Default:
{ width: 1200, height: 600, fonts: [] }

描述

此插件自动创建包含页面内容的图像。它与 metas 插件结合使用效果极佳,用于创建 Open Graph 元标签。

Satori 用于生成 SVG 图像(然后使用 Sharp 将其转换为 PNG)。生成的图像 URL 保存在 metas.image 变量中,因此会被 metas 插件检测到(metas 插件必须在 og_images 之后添加)。

安装

在你的 _config.ts 文件中导入此插件以使用它:

import lume from "lume/mod.ts";
import ogImages from "lume/plugins/og_images.ts";
import metas from "lume/plugins/metas.ts";

const site = lume();

site.use(ogImages());
site.use(metas()); /* 可选,用于生成 <meta> 标签 */

export default site;

用法

要生成图像,你需要指定用于渲染 HTML 内容的布局,使用变量 openGraphLayout。例如:

---
openGraphLayout: /layouts/og_images.jsx
---

正如 layout 变量用于渲染页面并生成 HTML 一样,openGraphLayout 用于渲染页面并生成 Open Graph 图像。你可以使用 _data 文件为所有页面设置相同的布局,或为每个目录设置不同的布局。

Satori 库

Satori 是用于生成图像的库,并且 仅接受 JSX 元素(或类似 React 元素的对象)。例如:

/** @jsxImportSource npm:react@18.2.0 */

export default function ({ title, description }) {
  return (
    <div
      style={{
        height: "100%",
        width: "100%",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "#fff",
        fontSize: 32,
        fontWeight: 600,
      }}
    >
      <svg
        width="75"
        viewBox="0 0 75 65"
        fill="#000"
        style={{ margin: "0 75px" }}
      >
        <path d="M37.59.25l36.95 64H.64l36.95-64z"></path>
      </svg>
      <div style={{ marginTop: 40 }}>{title}</div>
      <div>{description}</div>
    </div>
  );
}

正如你所见,此布局类似于 Lume 中的标准 JSX 布局。页面数据在第一个参数中传递,因此你可以使用标题、描述或任何其他变量来生成图像。

有关 Satori 支持的所有 CSS 属性和 HTML 元素的完整列表,请参阅文档。

你可以使用 Playground 进行测试和实验。

字体和配置

默认情况下,此插件加载 Inter 字体。 如果你想使用自定义字体,你必须配置 Satori 来加载它们。例如:

import { read } from "lume/core/utils/read.ts";

/** 带有默认值的示例 */
site.use(openGraphImages({
  satori: {
    width: 1200,
    height: 600,
    fonts: [
      {
        name: "inter",
        weight: 400,
        style: "normal",
        data: await read(
          "https://cdn.jsdelivr.net/npm/@xz/fonts@1/serve/src/inter/Inter-Regular.woff",
          true,
        ),
      },
      {
        name: "inter",
        weight: 700,
        style: "normal",
        data: await read(
          "https://cdn.jsdelivr.net/npm/@xz/fonts@1/serve/src/inter/Inter-SemiBold.woff",
          true,
        ),
      },
    ],
  },
}));

输出

输出图像的路径与 HTML 页面相同,但扩展名是 .png 而不是 .html。例如:

  • 页面 /example.html 生成图像 /example.png
  • 页面 /example/ 生成图像 /example/index.png

图像 URL 保存在 metas.image 变量中,可以随时与 metas 插件一起使用。