你的第一个原生插件

本页内容

本指南将引导您从零开始构建原生插件。原生插件与您的 Astro 站点在同一进程中运行,可完全访问运行时,包括 React 管理页面、Portable Text 组件和页面片段。

如果您尚未决定要使用原生插件还是沙盒插件,请先阅读选择插件格式

两个部分,一个或两个文件

  1. 描述符工厂 — 返回一个包含 format: "native"PluginDescriptor
  2. createPlugin(options) 函数 — 运行时部分。
my-native-plugin/
├── src/
│   ├── index.ts          # 描述符工厂 + createPlugin
│   ├── admin.tsx         # React 管理组件(可选)
│   └── astro/
│       └── index.ts
├── package.json
└── tsconfig.json

设置包

{
	"name": "@my-org/plugin-analytics",
	"version": "0.1.0",
	"type": "module",
	"main": "dist/index.js",
	"exports": {
		".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
		"./admin": { "types": "./dist/admin.d.ts", "import": "./dist/admin.js" }
	},
	"files": ["dist"],
	"peerDependencies": { "emdash": "*", "react": "^18.0.0" }
}

编写描述符和运行时

import { definePlugin } from "emdash";
import type { PluginDescriptor } from "emdash";

export interface AnalyticsOptions { enabled?: boolean; maxEvents?: number; }

export function analyticsPlugin(options: AnalyticsOptions = {}): PluginDescriptor {
	return {
		id: "analytics", version: "0.1.0", format: "native",
		entrypoint: "@my-org/plugin-analytics", options,
		adminEntry: "@my-org/plugin-analytics/admin",
		adminPages: [{ path: "/dashboard", label: "Dashboard", icon: "chart" }],
		adminWidgets: [{ id: "events-today", title: "Events Today", size: "third" }],
	};
}

export function createPlugin(options: AnalyticsOptions = {}) {
	const maxEvents = options.maxEvents ?? 100;
	return definePlugin({
		id: "analytics", version: "0.1.0",
		capabilities: ["network:request"],
		allowedHosts: ["api.analytics.example.com"],
		storage: { events: { indexes: ["type", "createdAt"] } },
		admin: {
			entry: "@my-org/plugin-analytics/admin",
			settingsSchema: {
				trackingId: { type: "string", label: "Tracking ID" },
				enabled: { type: "boolean", label: "Enabled", default: options.enabled ?? true },
			},
			pages: [{ path: "/dashboard", label: "Dashboard", icon: "chart" }],
			widgets: [{ id: "events-today", title: "Events Today", size: "third" }],
		},
		hooks: {
			"plugin:install": async (_event, ctx) => { ctx.log.info("Analytics plugin installed", { maxEvents }); },
			"content:afterSave": async (event, ctx) => {
				const enabled = await ctx.kv.get<boolean>("settings:enabled");
				if (enabled === false) return;
				await ctx.storage.events.put(`evt_${Date.now()}`, {
					type: "content:save", contentId: event.content.id, createdAt: new Date().toISOString(),
				});
			},
		},
		routes: {
			stats: {
				handler: async (ctx) => {
					const today = new Date().toISOString().split("T")[0];
					const count = await ctx.storage.events.count({ createdAt: { gte: today } });
					return { today: count };
				},
			},
		},
	});
}

export default createPlugin;

插件 ID 规则

id 字段必须匹配 /^[a-z][a-z0-9_-]*$/

版本格式

使用语义化版本控制。

注册插件

import { defineConfig } from "astro/config";
import emdash from "emdash/astro";
import { analyticsPlugin } from "@my-org/plugin-analytics";

export default defineConfig({
	integrations: [
		emdash({ plugins: [analyticsPlugin({ enabled: true, maxEvents: 500 })] }),
	],
});

设置 UI

字段类型:stringnumberbooleanselectsecreturlemail。设置持久化到同一个插件专属 KV 存储中 — 使用 ctx.kv.get<T>("settings:<key>") 读取。

完整示例 — 审计日志插件

import { definePlugin } from "emdash";
import type { PluginDescriptor } from "emdash";

interface AuditEntry {
	timestamp: string; action: "create" | "update" | "delete";
	collection: string; resourceId: string;
}

export function auditLogPlugin(): PluginDescriptor {
	return { id: "audit-log", version: "0.1.0", format: "native", entrypoint: "@emdash-cms/plugin-audit-log" };
}

export function createPlugin() {
	return definePlugin({
		id: "audit-log", version: "0.1.0",
		storage: {
			entries: { indexes: ["timestamp", "action", "collection", ["collection", "timestamp"], ["action", "timestamp"]] },
		},
		admin: {
			settingsSchema: { retentionDays: { type: "number", label: "保留天数", description: "保留条目的天数。0 = 永久。", default: 90, min: 0, max: 365 } },
			pages: [{ path: "/history", label: "Audit History", icon: "history" }],
			widgets: [{ id: "recent-activity", title: "Recent Activity", size: "half" }],
		},
		hooks: {
			"content:afterSave": {
				priority: 200,
				handler: async (event, ctx) => {
					await ctx.storage.entries.put(`${Date.now()}-${event.content.id}`, {
						timestamp: new Date().toISOString(), action: event.isNew ? "create" : "update",
						collection: event.collection, resourceId: event.content.id as string,
					});
				},
			},
			"content:afterDelete": {
				priority: 200,
				handler: async (event, ctx) => {
					await ctx.storage.entries.put(`${Date.now()}-${event.id}`, {
						timestamp: new Date().toISOString(), action: "delete",
						collection: event.collection, resourceId: event.id,
					});
				},
			},
		},
		routes: {
			recent: {
				handler: async (ctx) => {
					const result = await ctx.storage.entries.query({ orderBy: { timestamp: "desc" }, limit: 10 });
					return { entries: result.items.map((item) => ({ id: item.id, ...(item.data as AuditEntry) })) };
				},
			},
		},
	});
}

export default createPlugin;

测试

  1. 创建一个安装了 EmDash 的测试站点。
  2. astro.config.mjs 中注册您的插件。
  3. 启动开发服务器,通过创建、更新或删除内容来触发钩子。
  4. 检查控制台中的 ctx.log 输出,并通过 API 路由验证存储。

下一步