將 EmDash 新增到現有 Astro 專案

本頁內容

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 了解兩者如何共存。

驗證安裝

  1. 啟動開發伺服器:

    npm run dev
  2. 開啟 http://localhost:4321/_emdash/admin 並完成設定精靈。

  3. 建立並發布一篇文章,然後從頁面查詢它:

    ---
    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.json Pages 不接受。如果您的網站目前部署在 Pages 上,請先遷移到 Workers
  • 繫結必須存在於您的 wrangler.jsonc 中。 至少需要一個用於資料庫的 D1 繫結和一個用於媒體的 R2 繫結,與 astro.config.mjs 中的繫結名稱相符。

疑難排解

症狀原因修復
管理介面卡在 “Loading EmDash…”@astrojs/react 未註冊react() 新增到 integrations
live.config.tsCould not resolve "astro:content"Astro 版本低於 6升級 Astro
getEmDashCollection 回傳錯誤缺少 src/live.config.ts新增 Live Collections 載入器
關於未解析套件的建置錯誤對等依賴未安裝明確安裝 @astrojs/reactreactreact-dom
內容變更不顯示頁面被預先呈現在動態頁面上設定 export const prerender = false

下一步