外掛程式可以向 Portable Text 編輯器新增自訂區塊類型 —— YouTube 嵌入、程式碼片段、圖片庫,以及預設區塊集合未涵蓋的任何內容。沙盒外掛程式可以宣告這些區塊的編輯 UI(使用 Block Kit 欄位),但在公開網站上渲染它們的 Astro 元件必須在建置時從 npm 載入。這就是需要原生外掛程式的部分。
如果您的外掛程式只需要編輯側欄位,並且有其他人提供渲染元件(或網站在本地提供),您可以保持沙盒狀態。如果外掛程式也需要提供渲染元件,則需要使用原生外掛程式。
宣告區塊類型
沙盒外掛程式和原生外掛程式都可以宣告區塊類型。原生外掛程式在 definePlugin() 內的 admin.portableTextBlocks 下執行此操作:
admin: {
portableTextBlocks: [
{
type: "youtube",
label: "YouTube Video",
icon: "video", // video, code, link, link-external
placeholder: "Paste YouTube URL...",
fields: [ // Block Kit fields for the editing UI
{ type: "text_input", action_id: "id", label: "YouTube URL" },
{ type: "text_input", action_id: "title", label: "Title" },
{ type: "text_input", action_id: "poster", label: "Poster Image URL" },
],
},
],
},
每個區塊類型定義:
type— 區塊類型名稱(在 Portable Text 的_type中使用)。label— 在編輯器的斜線命令選單中顯示的名稱。icon—video、code、link或link-external。預設回退到通用立方體。placeholder— 輸入佔位符文字。fields— 用於編輯的 Block Kit 表單欄位。如果省略,將顯示簡單的 URL 輸入。
在公開網站上渲染
要在公開網站上渲染區塊類型,請從 componentsEntry 匯出 Astro 元件。匯出名稱必須是 blockComponents:
import YouTube from "./YouTube.astro";
import CodePen from "./CodePen.astro";
export const blockComponents = {
youtube: YouTube,
codepen: CodePen,
};
在描述符上設定 componentsEntry:
export function myPlugin(): PluginDescriptor {
return {
id: "embeds",
version: "1.0.0",
format: "native",
entrypoint: "@my-org/embeds",
componentsEntry: "@my-org/embeds/astro",
};
}
EmDash 會自動將外掛程式區塊元件合併到 <PortableText> 中 —— 網站作者無需匯入任何內容。使用者提供的元件(在網站的 <PortableText> 的 components 屬性中宣告)優先於外掛程式預設值。
套件匯出
將 ./astro 匯出新增到 package.json:
{
"exports": {
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
"./admin": { "types": "./dist/admin.d.ts", "import": "./dist/admin.js" },
"./astro": { "types": "./dist/astro/index.d.ts", "import": "./dist/astro/index.js" }
}
}
./astro 匯出是伺服器端的(Astro SSR),./admin 匯出是瀏覽器端的(React),"." 匯出是描述符 + createPlugin。將它們儲存在單獨的檔案中,因為它們針對不同的環境進行打包。
沙盒友善的變體
如果您希望外掛程式是沙盒的,但仍然提供預設的渲染體驗,通常的模式是:
- 在市場上發布沙盒外掛程式(僅編輯欄位)。
- 在 npm 上發布單獨的配套原生套件,提供 Astro 渲染元件。
- 記錄兩者:最終使用者從市場安裝沙盒外掛程式,並透過
npm install安裝配套套件進行渲染。
這將一步安裝換成了保持編輯器側沙盒化。當涉及區塊渲染時,完全原生更簡單,但這種拆分仍然是一個選項。