將 EmDash 新增到現有 Astro 專案

本頁內容

npm create emdash@latest 提供了一個預設好的專案,但 EmDash 也可以整合到您現有的 Astro 網站中。本指南逐一介紹入門範本通常為您處理的每個需求。

先決條件

  • Astro 6 或更高版本 — 如果您使用的是之前的主要版本,請先升級(npx @astrojs/upgrade
  • Node.js v22.12.0 或更高版本(不支援奇數版本)
  • 伺服器輸出 — EmDash 在執行時提供內容,因此您的專案需要 output: "server" 和一個適配器

安裝套件

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

對於本機 SQLite 資料庫:

npm install better-sqlite3

註冊整合

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",
			}),
		}),
	],
});

新增即時集合載入器

import { defineLiveCollection } from "astro:content";
import { emdashLoader } from "emdash/runtime";

export const collections = {
	_emdash: defineLiveCollection({ loader: emdashLoader() }),
};

驗證安裝

  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 取得完整設定。

疑難排解

症狀原因解決方案
管理後台停在 “Loading EmDash…”@astrojs/react 未註冊react() 加入 integrations
Could not resolve "astro:content"Astro 版本低於 6升級 Astro
getEmDashCollection 回傳錯誤缺少 src/live.config.ts新增載入器
建置錯誤未安裝 peer 相依套件安裝 @astrojs/reactreactreact-dom
內容變更未顯示頁面被預先渲染設定 export const prerender = false

後續步驟