npm create emdash@latest 提供一个预配置的项目,但 EmDash 也可以嫁接到您已有的 Astro 网站上。本指南逐一说明起始模板通常为您处理的每个要求 — 每一个缺失时都会产生令人困惑的错误,因此请按顺序完成检查清单。
前提条件
- Astro 6 或更高版本 — 如果在更早的主版本上,请先升级(
npx @astrojs/upgrade) - Node.js v22.16.0 或更高版本(不支持奇数版本)
- 服务器输出 — EmDash 在运行时提供内容,因此您的项目需要
output: "server"和一个适配器(Node、Cloudflare 等)
安装软件包
将 EmDash 与其所需的对等依赖一起安装。React 驱动 /_emdash/admin 的管理界面;即使您的网站本身不使用 React,也需要它。
npm
npm install emdash @astrojs/react react react-dom pnpm
pnpm add emdash @astrojs/react react react-dom yarn
yarn add emdash @astrojs/react react react-dom 要部署到 Cloudflare?还需要添加 Cloudflare 包 — 部署到 Cloudflare 指南中有详细说明:
npm install @astrojs/cloudflare @emdash-cms/cloudflare
注册集成
将 react() 和 emdash() 都添加到您的 integrations 数组中。注册 @astrojs/react 不是可选的:仅安装软件包是不够的,没有集成的话管理界面可以构建但永远不会水合 — 页面会一直停在 “Loading EmDash…”。
import { defineConfig } from "astro/config";
import node from "@astrojs/node";
import react from "@astrojs/react";
import emdash, { local } from "emdash/astro";
import { sqlite } from "emdash/db";
export default defineConfig({
output: "server",
adapter: node({ mode: "standalone" }),
integrations: [
react(),
emdash({
database: sqlite({ url: "file:./data.db" }),
storage: local({
directory: "./uploads",
baseUrl: "/_emdash/api/media/file",
}),
}),
],
});
添加 Live Collections 加载器
创建 src/live.config.ts,使 Astro 的内容层可以解析 EmDash 内容。没有它,getEmDashCollection / getEmDashEntry 没有可路由的 Live Collection。
import { defineLiveCollection } from "astro:content";
import { emdashLoader } from "emdash/runtime";
export const collections = {
_emdash: defineLiveCollection({ loader: emdashLoader() }),
};
您现有的 src/content.config.ts(基于文件的集合)会继续工作 — 请参阅 面向 Astro 开发者的 EmDash 了解两者如何共存。
验证安装
-
启动开发服务器:
npm run dev -
打开
http://localhost:4321/_emdash/admin并完成设置向导。 -
创建并发布一篇文章,然后从页面查询它:
--- import { getEmDashCollection } from "emdash"; const { entries: posts } = await getEmDashCollection("posts", { status: "published", }); --- <ul>{posts.map((post) => <li>{post.data.title}</li>)}</ul>
部署到 Cloudflare
请按照部署到 Cloudflare 进行完整设置(D1 数据库、R2 媒体桶、定时触发器)。现有项目特别容易在两个地方出问题:
- 使用 Cloudflare Workers,而不是 Pages。
@astrojs/cloudflare适配器输出的wrangler.jsonPages 不接受。如果您的网站当前部署在 Pages 上,请先迁移到 Workers。 - 绑定必须存在于您的
wrangler.jsonc中。 至少需要一个用于数据库的 D1 绑定和一个用于媒体的 R2 绑定,与astro.config.mjs中的绑定名称匹配。
故障排除
| 症状 | 原因 | 修复 |
|---|---|---|
| 管理界面卡在 “Loading EmDash…” | @astrojs/react 未注册 | 将 react() 添加到 integrations |
live.config.ts 中 Could not resolve "astro:content" | Astro 版本低于 6 | 升级 Astro |
getEmDashCollection 返回错误 | 缺少 src/live.config.ts | 添加 Live Collections 加载器 |
| 关于未解析包的构建错误 | 对等依赖未安装 | 显式安装 @astrojs/react、react、react-dom |
| 内容更改不显示 | 页面被预渲染 | 在动态页面上设置 export const prerender = false |
下一步
- 面向 Astro 开发者的 EmDash — EmDash 概念如何映射到您已知的知识
- 处理内容 — 查询和渲染内容
- 部署到 Cloudflare — 将网站投入生产