Astro 网站构建器
使用 Astro 5 构建生产就绪的静态网站。涵盖作品集、电子书平台、博客、营销网站和文档。
何时使用
- 用户要求构建 Astro 网站、作品集或博客
- 用户希望部署到 Cloudflare Pages
- 用户需要一个带侧边栏导航的电子书/文档网站
- 用户想要一个包含站点地图、meta 标签、结构化数据的 SEO 优化静态网站
- 用户提及 "Astro"、"Cloudflare Pages"、"JAMstack 静态网站"
快速开始
# 创建项目
npm create astro@latest my-site -- --template minimal
cd my-site
# 核心依赖
npm install @astrojs/sitemap
# 构建 & 预览
npm run build # 输出到 dist/
npm run preview # 本地预览服务器
项目结构
project/
├── astro.config.mjs
├── package.json
├── tsconfig.json
├── public/
│ ├── robots.txt
│ └── _headers # Cloudflare 安全标头
├── src/
│ ├── layouts/
│ │ ├── BaseLayout.astro # 站点外壳 (header, footer, SEO)
│ │ └── EbookLayout.astro # 内容布局 (侧边栏, 进度条)
│ └── pages/
│ ├── index.astro # 主页
│ ├── blog.astro
│ └── ebook/
│ ├── index.astro # 电子书列表
│ └── video-editing/
│ └── index.astro # 单本电子书页面
└── dist/ # 构建输出 (部署此目录)
Astro 配置 (针对 Cloudflare 优化)
// astro.config.mjs
import { defineConfig } from 'astro/config';
import sitemap from '@astrojs/sitemap';
export default defineConfig({
site: 'https://yourdomain.com',
integrations: [sitemap()],
prefetch: true,
build: {
inlineStylesheets: 'auto', // 内联关键 CSS 以加快 FCP
},
});
SEO 模式 (BaseLayout)
每个页面通过 props 获得完整的 SEO:
---
export interface Props {
title: string;
description?: string;
canonical?: string;
image?: string;
type?: string; // 'website' | 'article'
}
---
在 <head> 中包含:
<title>(格式:页面标题 | 网站名称)<meta name="description"><link rel="canonical">- Open Graph 标签 (og:type, og:title, og:description, og:image, og:url)
- Twitter 卡片 meta 标签
- JSON-LD 结构化数据 (Person, Organization, Article 视情况而定)
<meta name="robots" content="index, follow">
EbookLayout 模式
适用于带侧边栏导航的长篇内容。完整 CSS 请参见 references/ebook-layout-css.md。
特性
- 侧边栏导航 — 固定左侧侧边栏,显示章节链接,通过滚动位置跟踪活动状态
- 进度条 — 固定的顶部条,显示阅读进度 (0-100%),渐变色填充 (青色到靛蓝)
- 返回顶部按钮 — 固定在右下角,滚动超过 400px 后显示
- 作者致谢 — 内容底部的头像圆圈 + 姓名/角色
- 代码块 — 深色背景 (
#1e293b),渐变色顶部强调条,等宽字体,水平滚动 - 表格 — 渐变色表头,交替行颜色,悬停效果,圆角边框
- 提示框 — 4 种类型:信息 (蓝色),警告 (琥珀色),提示 (绿色),危险 (红色),每种都带有 SVG 图标
- 打印样式 — 隐藏侧边栏/进度条/导航,展开内容,分页规则
- 响应式 — 3 个断点 (960px 隐藏侧边栏,600px 紧凑布局,移动端堆叠)
CSS 策略:在 <style slot="head"> 上使用 is:global
EbookLayout CSS 必须使用 is:global,这样样式才能应用于页面组件的插槽内容:
<style slot="head" is:global>
/* 此处的所有类都应用于插槽内容 */
.ebook-content h1 { ... }
.callout { ... }
.callout-info { ... }
</style>
如果没有 is:global,在 EbookLayout 中定义的 .callout-info 等类将不会应用于使用 <EbookLayout> 的页面组件中的元素。
EbookLayout Props 接口
export interface Props {
title: string;
description?: string;
chapters: { slug: string; title: string; number: number }[];
currentSlug: string;
ebookTitle: string;
ebookDescription?: string;
author?: string; // 默认为 'Ahmad Asri Zalmi'
}
内容页面模式
每个电子书页面定义章节数组并传递给 EbookLayout:
---
import EbookLayout from '../../../layouts/EbookLayout.astro';
const chapters = [
{ slug: 'index', title: 'Pendahuluan', number: 1 },
{ slug: 'topic-a', title: 'Topic A', number: 2 },
];
---
<EbookLayout title="页面标题" description="SEO 描述" chapters={chapters} currentSlug="ebook-别名" ebookTitle="电子书标题" ebookDescription="副标题" author="作者姓名">
<h1 id="index">页面标题</h1>
<p class="ebook-subtitle">副标题文本</p>
<div class="ebook-meta">
<!-- SVG 用户图标 + 作者姓名 + SVG 日历图标 + 年份 -->
</div>
<!-- 章节,h2 id 与 slug 匹配 -->
</EbookLayout>
标题/头部块 (强制)
<h1 id="index">标题</h1>
<p class="ebook-subtitle">副标题</p>
<div class="ebook-meta">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
<span>作者姓名</span>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-left:0.5rem"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
<span>2026</span>
</div>
提示框 HTML (4 种类型)
<!-- 信息 (蓝色 #3b82f6) -->
<div class="callout callout-info">
<svg class="callout-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
<div class="callout-content"><strong>标题</strong><p>内容。</p></div>
</div>
<!-- 警告 (橙色 #f59e0b) -->
<div class="callout callout-warning">
<svg class="callout-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
<div class="callout-content"><strong>标题</strong><p>内容。</p></div>
</div>
<!-- 提示 (绿色 #22c55e) -->
<div class="callout callout-tip">
<svg class="callout-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
<div class="callout-content"><strong>标题</strong><p>内容。</p></div>
</div>
<!-- 危险 (红色 #ef4444) -->
<div class="callout callout-danger">
<svg class="callout-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
<div class="callout-content"><strong>标题</strong><p>内容。</p></div>
</div>
资源链接部分 (电子书末尾)
<div class="resource-links">
<h3>资源与链接</h3>
<ul>
<li>
<a href="https://..." target="_blank" rel="noopener">链接文本</a>
<span class="desc">简短描述</span>
</li>
</ul>
</div>
使用 set:html 的代码块
在 frontmatter 中定义代码字符串,使用 set:html 渲染:
---
const code_example = `# shell 命令
npm run build`;
---
<pre><code set:html={code_example}></code></pre>
侧边栏活动状态 (JS)
const navLinks = document.querySelectorAll('[data-nav-link]');
const headings = [];
navLinks.forEach(link => {
const id = link.getAttribute('href').slice(1);
const el = document.getElementById(id);
if (el) headings.push({ el, link });
});
const updateActive = () => {
let active = headings[0];
for (const h of headings) {
if (h.el.getBoundingClientRect().top <= 100) active = h;
}
navLinks.forEach(l => l.classList.remove('active'));
if (active) active.link.classList.add('active');
};
window.addEventListener('scroll', updateActive, { passive: true });
导入路径规则
Astro 使用 Vite 基于文件的路径。导入路径是相对于导入文件的:
| 文件位置 | 导入布局的来源 |
|---|---|
src/pages/index.astro | ../layouts/BaseLayout.astro |
src/pages/blog.astro | ../layouts/BaseLayout.astro |
src/pages/ebook/index.astro | ../../layouts/BaseLayout.astro |
src/pages/ebook/video-editing/index.astro | ../../../layouts/BaseLayout.astro |
从 src/ 开始计算目录深度以确定 ../ 段数。
Cloudflare Pages 部署
构建设置
| 设置 | 值 |
|---|---|
| 框架预设 | Astro |
| 构建命令 | npm run build |
| 构建输出目录 | dist |
| Node.js 版本 | 18+ (通过环境变量 NODE_VERSION 设置) |
安全标头 (public/_headers)
/*
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
/assets/*
Cache-Control: public, max-age=31536000, immutable
重定向 (public/_redirects)
/old-path /new-path 301
Wrangler CLI 部署 (直接上传)
# 先构建
npm run build
# 部署到 Cloudflare Pages
CLOUDFLARE_API_TOKEN=cfut_xxx CLOUDFLARE_ACCOUNT_ID=xxx \
npx wrangler pages deploy dist --project-name=my-site --branch=main
# 预览部署 (非 main 分支)
npx wrangler pages deploy dist --project-name=my-site --branch=staging
独立 HTML 一致性
当独立 HTML 电子书文件位于 public/ebook/ (绕过 Astro 布局) 时,它们需要手动注入共享的标头、侧边栏、配色方案和作者描述。请参见 references/standalone-html-consistency.md 了解完整模式,包括:
- 注入带有 logo + 导航的粘性标头 (使用内联 CSS 以避免冲突)
- 在固定侧边栏上方添加标头时,调整侧边栏
top/height - 配色方案统一 (CSS 变量、rgba、渐变 — 必须全部更新)
- 返回顶部按钮注入 (CSS + HTML + JS)
- 补丁工具 JS 嵌套陷阱 (补丁后始终验证闭合大括号)
- 作者描述一致性检查清单
陷阱
请参见 references/astro5-pitfalls.md 了解详细问题。摘要:
- HTML 中的花括号 —
{和}是 JSX 表达式。对代码块使用set:html。 lightningcss未打包 — 单独安装,或不要使用cssMinify: 'lightningcss'。- 导入路径深度 — 必须与目录结构完全匹配。
- 不要使用 emoji — 使用内联 SVG 图标 (来自 ebook-generator 技能的用户偏好)。
set:html仅用于 void/自闭合或带有 slot — 使用set:html时不能有子元素。- Astro 作用域 CSS —
<style>中的类在每个组件中都是作用域的。使用<style is:global>或:global(.class)来共享类。EbookLayout 必须使用<style slot="head" is:global>才能使样式应用于插槽内容。 data-astro-cid作用域不匹配 — BaseLayout 中的.container类不会应用于页面组件中的元素。需要全局类:.container、.btn、.section、.grid-*等。- JS 类切换 + 作用域 CSS = 静默失败 — 动态添加/删除类的 JavaScript (例如,IntersectionObserver 在滚动时添加
.fade-in) 不会匹配 Astro 的作用域选择器。Astro 将.fade-in作用域为.fade-in[data-astro-cid-xxxx],但 JS 添加了普通的.fade-in类。症状: 部分区域永远不可见 (opacity:0)。修复: (a) 对动画类使用<style is:global>,(b) 在作用域样式中使用:global(.fade-in),或 (c) 完全移除 CSS 动画类,让内容立即渲染。对于动画不关键的 SSR 站点,选项 (c) 最简单。完整详情请参见references/astro5-pitfalls.md#9。 - 独立 HTML 侧边栏偏移 — 向独立电子书 HTML 文件注入粘性标头时,始终将固定侧边栏的
top从0调整为标头高度 (~56px),并设置height: calc(100vh - 56px)。忘记此操作会导致侧边栏内容隐藏在标头后面。
反模式
- 不要在没有
npm install lightningcss的情况下使用cssMinify: 'lightningcss' - 不要在
<pre><code>块内放置{variable}— Astro 会将其解析为 JSX - 不要使用 emoji 作为图标 — 使用内联 SVG
- 不要省略 SEO 的
robots.txt和站点地图 - 不要忘记移动端的
<meta name="viewport"> - 不要硬编码站点 URL — 使用来自配置的
Astro.site