本指南將 EmDash 新增到 Astro 專案中,並透過一個已發布的條目驗證整合。 它使用 Node.js 適配器、SQLite 和本地媒體儲存,使完整路徑可以在一台 機器上運作。
開始之前
使用 Astro 6 或更高版本以及 Node.js 22.16 或更高版本。在專案中檢查兩個版本:
node --version
npx astro --version
本指南將網站變更為 Astro 的 server 輸出並設定 Node.js 適配器。這將
改變網站的建構和部署方式。如果專案已經使用其他伺服器適配器,
不要新增第二個。保留該適配器並遵循其部署要求;對於 Cloudflare,使用
Cloudflare Workers 指南。
在變更設定之前,提交或以其他方式儲存目前專案。
安裝 EmDash
-
安裝 EmDash、Node.js 適配器和 React 支援:
npm
npm install emdash @astrojs/node @astrojs/react react react-dompnpm
pnpm add emdash @astrojs/node @astrojs/react react react-domyarn
yarn add emdash @astrojs/node @astrojs/react react react-dom即使公開網站沒有 React 元件,EmDash 也會將 React 用於管理面板。
-
在
astro.config.mjs中註冊適配器、React 和 EmDash。如果檔案已包含其他 整合或設定,請保留它們並從此範例中新增相關條目:import node from "@astrojs/node"; import react from "@astrojs/react"; import { defineConfig } from "astro/config"; 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", }), }), ], });SQLite 將內容和內容模型儲存在
data.db中。本地儲存適配器將媒體寫入uploads/並透過 EmDash 的媒體路由提供服務。如果兩個路徑尚未排除, 請將它們新增到.gitignore。 -
建立
src/live.config.ts以將 EmDash 連接到 Astro 的內容系統:import { defineLiveCollection } from "astro:content"; import { emdashLoader } from "emdash/runtime"; export const collections = { _emdash: defineLiveCollection({ loader: emdashLoader() }), };如果專案已有
src/live.config.ts,請將_emdash條目新增到匯出的collections物件中,而不是取代檔案。用於基於檔案的集合的單獨src/content.config.ts可繼續並行運作。 -
產生本地加密金鑰並寫入
.env:npx emdash secrets generate --write .env確認
.env被.gitignore排除。該金鑰保護儲存在資料庫中的 外掛金鑰。取代或遺失金鑰會使這些加密值不可讀,因此在部署網站之前 請保留一份受保護的備份。
設定網站和內容
-
啟動開發伺服器:
npm run dev -
開啟
http://localhost:4321/_emdash/admin/。首次造訪會重新導向到設定精靈。 輸入網站詳情,建立管理員帳戶並註冊通行金鑰。由於此專案沒有種子檔案,設定將套用 EmDash 的內建起始模型。它建立 Posts 和 Pages 集合、標題和內容欄位,以及分類和標籤分類法。不會 新增範例條目。
-
開啟 Posts,選擇 New Post,輸入
EmDash is connected作為標題。選擇 Save 建立條目,然後選擇 Publish。
資料庫現在在內建 posts 集合中包含一個已發布的條目。下一步
從 Astro 頁面讀取它。
查詢條目
建立一個伺服器渲染的測試頁面,列出已發布的文章:
---
import { getEmDashCollection } from "emdash";
const { entries: posts, error } = await getEmDashCollection("posts");
if (error) {
throw error;
}
---
<h1>EmDash posts</h1>
<ul>
{posts.map((post) => <li>{post.data.title}</li>)}
</ul>
開啟 http://localhost:4321/emdash-test/。頁面顯示 EmDash is connected。如果你在管理面板中
變更並重新發布標題,重新載入此頁面將顯示更新後的標題。
在本地開發期間,EmDash 還會從目前內容模型產生 emdash-env.d.ts。
產生的宣告為 TypeScript 提供 posts 集合名稱及其 title 欄位。
不要手動編輯該產生檔案。
如果驗證失敗
- 如果管理介面停留在 Loading EmDash…,請檢查 Astro
integrations陣列中是否包含react()。 僅安裝@astrojs/react而不註冊是不夠的。 - 如果
getEmDashCollection()傳回有關即時集合的錯誤,請檢查src/live.config.ts是否 使用emdashLoader()匯出_emdash。 - 如果頁面在開發中有效但部署的編輯不顯示,請檢查頁面是否未預先渲染, 以及部署的應用程式是否使用伺服器輸出。
- 如果建構無法解析某個匯入,請重新執行安裝命令並確認五個套件 已新增到此專案而非其他工作區目錄。