opengraph-image 與 twitter-image
opengraph-image
和 twitter-image
檔案約定允許您為路由區段設定 Open Graph 和 Twitter 圖片。
這些設定對於當使用者在社交網路和通訊應用中分享您網站的連結時,顯示的圖片非常有用。
設定 Open Graph 和 Twitter 圖片有兩種方式:
圖片檔案 (.jpg, .png, .gif)
透過在路由區段中放置 opengraph-image
或 twitter-image
圖片檔案,來設定該區段的分享圖片。
Next.js 會評估該檔案並自動將適當的標籤添加到您應用的 <head>
元素中。
檔案約定 | 支援的檔案類型 |
---|---|
opengraph-image | .jpg , .jpeg , .png , .gif |
twitter-image | .jpg , .jpeg , .png , .gif |
opengraph-image.alt | .txt |
twitter-image.alt | .txt |
opengraph-image
在任何路由區段中添加 opengraph-image.(jpg|jpeg|png|gif)
圖片檔案。
twitter-image
在任何路由區段中添加 twitter-image.(jpg|jpeg|png|gif)
圖片檔案。
opengraph-image.alt.txt
在與 opengraph-image.(jpg|jpeg|png|gif)
圖片相同的路由區段中,添加一個 opengraph-image.alt.txt
檔案來設定其替代文字。
twitter-image.alt.txt
在與 twitter-image.(jpg|jpeg|png|gif)
圖片相同的路由區段中,添加一個 twitter-image.alt.txt
檔案來設定其替代文字。
使用程式碼生成圖片 (.js, .ts, .tsx)
除了使用實際圖片檔案外,您還可以透過程式碼生成圖片。
透過建立一個預設導出函式的 opengraph-image
或 twitter-image
路由,來生成路由區段的分享圖片。
檔案約定 | 支援的檔案類型 |
---|---|
opengraph-image | .js , .ts , .tsx |
twitter-image | .js , .ts , .tsx |
須知
- 預設情況下,生成的圖片會進行靜態優化(在構建時生成並緩存),除非它們使用了動態函式或未緩存的資料。
- 您可以在同一檔案中使用
generateImageMetadata
生成多個圖片。
生成圖片最簡單的方法是使用 next/og
中的 ImageResponse API。
屬性
預設導出函式接收以下屬性:
params
(可選)
一個物件,包含從根區段到 opengraph-image
或 twitter-image
所在區段的動態路由參數物件。
路由 | URL | params |
---|---|---|
app/shop/opengraph-image.js | /shop | undefined |
app/shop/[slug]/opengraph-image.js | /shop/1 | { slug: '1' } |
app/shop/[tag]/[item]/opengraph-image.js | /shop/1/2 | { tag: '1', item: '2' } |
app/shop/[...slug]/opengraph-image.js | /shop/1/2 | { slug: ['1', '2'] } |
返回值
預設導出函式應返回 Blob
| ArrayBuffer
| TypedArray
| DataView
| ReadableStream
| Response
其中之一。
須知:
ImageResponse
符合此返回類型。
配置導出
您可以選擇性地透過從 opengraph-image
或 twitter-image
路由導出 alt
、size
和 contentType
變數來配置圖片的元數據。
選項 | 類型 |
---|---|
alt | string |
size | { width: number; height: number } |
contentType | string - 圖片 MIME 類型 |
alt
size
contentType
路由區段配置
opengraph-image
和 twitter-image
是特殊的路由處理器,可以使用與頁面和佈局相同的路由區段配置選項。
選項 | 類型 | 預設值 |
---|---|---|
dynamic | 'auto' | 'force-dynamic' | 'error' | 'force-static' | 'auto' |
revalidate | false | 'force-cache' | 0 | number | false |
runtime | 'nodejs' | 'edge' | 'nodejs' |
preferredRegion | 'auto' | 'global' | 'home' | string | string[] | 'auto' |
範例
使用外部資料
此範例使用 params
物件和外部資料來生成圖片。
版本歷史
版本 | 變更 |
---|---|
v13.3.0 | 引入 opengraph-image 和 twitter-image 。 |