{
  "id": "add-pagefind-search-to-astro",
  "type": "playbooks",
  "category": "playbooks",
  "locale": "zh",
  "url": "/zh/playbooks/add-pagefind-search-to-astro",
  "title": "Prompt-to-PR：为Astro站点添加Pagefind搜索",
  "description": "完整的标准操作流程——从首次提示到PR描述，为Astro站点添加静态、无后端搜索功能。",
  "tools": [
    "Cursor",
    "Claude Code"
  ],
  "stack": [
    "Astro",
    "TypeScript"
  ],
  "tags": [
    "search",
    "astro",
    "pagefind"
  ],
  "difficulty": "easy",
  "updated": "2026-06-08",
  "markdown": "完整的操作手册：需求、首次提示、预期变更、审查、测试、\n常见失败、修复提示以及PR描述。\n\n## 1. 需求\n\n为静态Astro站点添加全文搜索，无需服务器和数据库。\n\n## 2. 首次提示\n\n```txt title=\"First Prompt\"\nAdd Pagefind search to this Astro static site.\n\n- Add `pagefind` as a devDependency.\n- Update the build script to run `astro build && pagefind --site dist`.\n- Create a `/search` page that mounts Pagefind UI from `/pagefind/pagefind-ui.js`.\n- Mark the main article body with `data-pagefind-body` and add\n  `data-pagefind-ignore` to nav/footer.\n- Do not introduce a server adapter; this stays fully static.\n```\n\n## 3. 预期文件变更\n\n```txt\npackage.json                 (build script)\nsrc/pages/search.astro       (new)\nsrc/layouts/BaseLayout.astro (data-pagefind-ignore on chrome)\n```\n\n## 4. 审查清单\n\n- 构建脚本在 `astro build` *之后*运行Pagefind。\n- 搜索页面在 `astro dev` 中优雅降级（索引仅在构建后存在）。\n- 导航/页脚被排除在索引之外。\n\n## 5. 测试命令\n\n```bash\nbun run build\nbun run preview\n# open /search and query a known term\n```\n\n## 6. 常见失败\n\n- 在脚本加载前挂载Pagefind UI → `PagefindUI is not defined`。\n- 在构建前运行Pagefind，导致索引为空。\n\n## 7. 修复提示\n\n```txt title=\"Fix Prompt\"\nPagefind indexed an empty site. Ensure the build runs `astro build` first,\nthen `pagefind --site dist`, and that the UI script loads before init.\n```\n\n## 8. PR描述\n\n```md title=\"PR description\"\nAdd static full-text search via Pagefind. Indexes `dist` at build time;\nno backend. New `/search` page; nav/footer excluded from the index.\n```"
}