Astro Starlight 使用教程
简介
Astro Starlight 是基于 Astro 框架的高性能文档主题,具有框架无关、零 JS 默认、Islands Architecture 等特性,是 2025 年性能和灵活度最佳的文档生成工具。
核心优势
- ⚡ 极致性能 - 默认零 JavaScript,页面加载速度最快
- 🎨 框架无关 - 可混合使用 React、Vue、Svelte、Solid 等
- 🏝️ Islands Architecture - 部分水合,按需加载交互组件
- 📱 响应式设计 - 移动端友好,自适应布局
- 🌙 暗黑模式 - 内置暗黑主题切换
- 🔍 全文搜索 - 开箱即用的搜索功能
- 🌐 国际化 - 多语言支持
- ♿ 无障碍 - WCAG 2.0 AA 标准
- 📊 SEO 优化 - 搜索引擎友好
快速开始
1. 创建新项目
# 使用 npm
npm create astro@latest -- --template starlight
# 使用 pnpm
pnpm create astro --template starlight
# 使用 yarn
yarn create astro --template starlight
2. 项目结构
my-docs/
├── src/
│ ├── content/
│ │ ├── docs/ # 文档内容(Markdown 文件)
│ │ │ ├── index.md
│ │ │ ├── guides/
│ │ │ └── reference/
│ │ └── config.ts # 内容集合配置
│ └── env.d.ts
├── astro.config.mjs # Astro 配置
├── package.json
└── tsconfig.json
3. 启动开发服务器
# 安装依赖
npm install
# 启动开发服务器
npm run dev
# 访问 http://localhost:4321
4. 构建生产版本
npm run build
# 预览构建结果
npm run preview
配置指南
基础配置 (astro.config.mjs)
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
export default defineConfig({
integrations: [
starlight({
// 网站标题
title: '我的文档站',
// 社交链接
social: {
github: 'https://github.com/username/repo',
twitter: 'https://twitter.com/username',
},
// 侧边栏配置
sidebar: [
{
label: '开始',
items: [
{ label: '介绍', link: '/intro/' },
{ label: '快速开始', link: '/getting-started/' },
],
},
{
label: '指南',
autogenerate: { directory: 'guides' },
},
{
label: 'API 参考',
autogenerate: { directory: 'reference' },
},
],
// 自定义 CSS
customCss: [
'./src/styles/custom.css',
],
// Logo 配置
logo: {
src: './src/assets/logo.svg',
replacesTitle: true,
},
// 页脚配置
editLink: {
baseUrl: 'https://github.com/username/repo/edit/main/',
},
// 最后更新时间
lastUpdated: true,
// 页脚
credits: true,
}),
],
});
国际化配置
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
export default defineConfig({
integrations: [
starlight({
title: 'My Docs',
// 配置多语言
locales: {
root: {
label: 'English',
lang: 'en',
},
zh: {
label: '简体中文',
lang: 'zh-CN',
},
ja: {
label: '日本語',
lang: 'ja',
},
},
// 默认语言
defaultLocale: 'root',
}),
],
});
编写文档
Markdown 文件基础
创建文档文件 src/content/docs/example.md:
---
title: 示例页面
description: 这是一个示例文档页面
---
# 欢迎使用 Starlight
这是文档内容。
## 功能特性
- 快速
- 灵活
- 易用
## 代码示例
\`\`\`javascript
function hello() {
console.log('Hello, Starlight!');
}
\`\`\`
Frontmatter 配置
---
# 页面标题(必需)
title: 页面标题
# 页面描述(用于 SEO)
description: 页面描述
# 侧边栏标签(可选,默认使用 title)
sidebar:
label: 自定义侧边栏标签
order: 1 # 排序
badge:
text: 新功能
variant: tip
# 页面模板
template: doc # doc(默认)、splash(首页模板)
# 显示目录
tableOfContents:
minHeadingLevel: 2
maxHeadingLevel: 4
# 上一页/下一页导航
prev: false # 或链接对象
next:
link: /guides/next-page/
label: 下一步
# 编辑链接
editUrl: https://github.com/username/repo/edit/main/src/content/docs/example.md
# 最后更新
lastUpdated: 2025-11-08
# Hero 配置(splash 模板)
hero:
tagline: 简洁有力的标语
image:
file: ../../assets/hero.png
alt: 图片描述
actions:
- text: 快速开始
link: /getting-started/
icon: right-arrow
variant: primary
- text: 查看 GitHub
link: https://github.com/username/repo
icon: external
variant: minimal
---
页面内容...
Splash 首页模板示例
---
title: 欢迎使用我的项目
template: splash
hero:
tagline: 一个现代化的解决方案,让开发更简单
image:
file: ../../assets/hero.png
actions:
- text: 开始使用
link: /getting-started/
icon: right-arrow
variant: primary
- text: 查看文档
link: /docs/
variant: secondary
---
import { Card, CardGrid } from '@astrojs/starlight/components';
## 核心特性
<CardGrid\>
\<Card title="快速" icon="rocket"\>
基于 Vite 构建,开发体验极佳
</Card\>
\<Card title="灵活" icon="puzzle"\>
框架无关,支持多种 UI 框架
</Card\>
\<Card title="优化" icon="seti:config"\>
默认优化,性能开箱即用
</Card\>
\<Card title="易用" icon="approve-check"\>
简单配置,快速上手
</Card\>
</CardGrid\>
使用内置组件
Starlight 提供了丰富的内置组件。
Tabs(标签页)
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs\>
\<TabItem label="npm"\>
\`\`\`bash
npm install package-name
\`\`\`
</TabItem\>
\<TabItem label="pnpm"\>
\`\`\`bash
pnpm add package-name
\`\`\`
</TabItem\>
\<TabItem label="yarn"\>
\`\`\`bash
yarn add package-name
\`\`\`
</TabItem\>
</Tabs\>
Card(卡片)
import { Card, CardGrid } from '@astrojs/starlight/components';
\<Card title="注意" icon="warning"\>
这是一个重要提示
</Card\>
<CardGrid\>
\<Card title="特性 1" icon="rocket"\>
描述内容
</Card\>
\<Card title="特性 2" icon="star"\>
描述内容
</Card\>
</CardGrid\>
Aside(侧边提示)
:::note
这是一个普通提示
:::
:::tip
这是一个小技巧
:::
:::caution
这是一个警告
:::
:::danger
这是一个危险警告
:::
:::note[自定义标题]
自定义标题的提示框
:::
Code(代码高亮)
```javascript title="app.js" {2-4} showLineNumbers
function example() {
// 这几行会被高亮
console.log('Hello');
console.log('World');
}
```
```diff lang="javascript"
- const old = 'removed';
+ const new = 'added';
```
Steps(步骤)
import { Steps } from '@astrojs/starlight/components';
<Steps\>
1. 第一步
执行这个操作
2. 第二步
执行下一个操作
3. 完成!
</Steps\>
Badge(徽章)
import { Badge } from '@astrojs/starlight/components';
\<Badge text="新功能" variant="tip" size="small" /\>
\<Badge text="已废弃" variant="caution" size="medium" /\>
\<Badge text="实验性" variant="danger" size="large" /\>
LinkCard(链接卡片)
import { LinkCard, CardGrid } from '@astrojs/starlight/components';
<LinkCard
title="查看更多"
description="点击了解详细信息"
href="/more-info/"
/\>
<CardGrid\>
\<LinkCard title="指南" href="/guides/" /\>
\<LinkCard title="参考" href="/reference/" /\>
</CardGrid\>
混合使用其他框架(Islands)
安装 React
npm install @astrojs/react react react-dom
astro.config.mjs:
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
import react from '@astrojs/react';
export default defineConfig({
integrations: [
starlight({ /* ... */ }),
react(),
],
});
创建 React 组件
src/components/Counter.tsx:
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div\>
<p\>Count: {count}</p\>
<button onClick={() =\> setCount(count + 1)}\>
Increment
</button\>
</div\>
);
}
在文档中使用
---
title: 交互示例
---
import Counter from '../../components/Counter';
# 交互式组件
<Counter client:load /\>
Client 指令说明:
client:load- 页面加载时立即水合client:idle- 页面空闲时水合client:visible- 组件可见时水合client:media- 媒体查询匹配时水合client:only- 仅在客户端渲染
同样适用于 Vue、Svelte 等
# Vue
npm install @astrojs/vue vue
# Svelte
npm install @astrojs/svelte svelte
# Solid
npm install @astrojs/solid-js solid-js
自定义样式
创建自定义 CSS
src/styles/custom.css:
/* 自定义颜色 */
:root {
--sl-color-accent-low: #1e3a8a;
--sl-color-accent: #3b82f6;
--sl-color-accent-high: #93c5fd;
--sl-color-white: #ffffff;
--sl-color-gray-1: #f3f4f6;
--sl-color-gray-2: #e5e7eb;
--sl-color-gray-3: #d1d5db;
--sl-color-gray-4: #9ca3af;
--sl-color-gray-5: #6b7280;
--sl-color-gray-6: #374151;
--sl-color-black: #111827;
}
/* 暗黑模式 */
:root[data-theme='dark'] {
--sl-color-accent-low: #1e3a8a;
--sl-color-accent: #60a5fa;
--sl-color-accent-high: #dbeafe;
}
/* 自定义字体 */
:root {
--sl-font: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
--sl-font-mono: 'Fira Code', 'Consolas', monospace;
}
/* 自定义组件样式 */
.sl-markdown-content {
font-size: 1.05rem;
line-height: 1.75;
}
引入 CSS:
// astro.config.mjs
export default defineConfig({
integrations: [
starlight({
customCss: [
'./src/styles/custom.css',
],
}),
],
});
高级功能
自动生成侧边栏
sidebar: [
{
label: '指南',
// 自动从目录生成
autogenerate: { directory: 'guides' },
},
{
label: 'API',
collapsed: true, // 默认折叠
autogenerate: { directory: 'api' },
},
]
搜索配置
// 使用 Pagefind(默认)
export default defineConfig({
integrations: [
starlight({
// 搜索默认启用
}),
],
});
// 使用 Algolia DocSearch
export default defineConfig({
integrations: [
starlight({
components: {
Search: './src/components/Search.astro',
},
}),
],
});
自定义组件覆盖
export default defineConfig({
integrations: [
starlight({
components: {
// 覆盖默认头部
Header: './src/components/CustomHeader.astro',
// 覆盖默认页脚
Footer: './src/components/CustomFooter.astro',
// 覆盖侧边栏
Sidebar: './src/components/CustomSidebar.astro',
},
}),
],
});
插件扩展
# 安装社区插件
npm install starlight-plugin-name
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
import starlightPlugin from 'starlight-plugin-name';
export default defineConfig({
integrations: [
starlight({
plugins: [
starlightPlugin({
// 插件配置
}),
],
}),
],
});
部署
静态部署
# 构建静态文件
npm run build
# 输出目录:dist/
Vercel 部署
- 连接 GitHub 仓库
- Vercel 自动检测 Astro 项目
- 自动部署
或使用 Vercel CLI:
npm install -g vercel
vercel
Netlify 部署
netlify.toml:
[build]
command = "npm run build"
publish = "dist"
[[plugins]]
package = "@netlify/plugin-lighthouse"
GitHub Pages 部署
astro.config.mjs:
export default defineConfig({
site: 'https://username.github.io',
base: '/repo-name',
// ...
});
.github/workflows/deploy.yml:
name: Deploy to GitHub Pages
on:
push:
branches: [ main ]
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npm run build
- uses: actions/upload-pages-artifact@v3
with:
path: ./dist
deploy:
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/deploy-pages@v4
id: deployment
Cloudflare Pages
npm run build
在 Cloudflare Pages 控制台:
- 构建命令:
npm run build - 输出目录:
dist
最佳实践
1. 文档结构组织
src/content/docs/
├── index.md # 首页
├── getting-started/
│ ├── installation.md
│ └── quick-start.md
├── guides/
│ ├── basics/
│ └── advanced/
├── api/
│ ├── components/
│ └── utilities/
└── contributing.md
2. 使用 TypeScript
src/content/config.ts:
import { defineCollection } from 'astro:content';
import { docsSchema } from '@astrojs/starlight/schema';
export const collections = {
docs: defineCollection({ schema: docsSchema() }),
};
3. 性能优化
- 使用
client:visible延迟加载交互组件 - 压缩图片资源
- 使用 WebP 格式
- 启用缓存
4. SEO 优化
---
title: 页面标题 | 站点名称
description: 详细的页面描述,包含关键词
---
5. 代码示例管理
import Code from '@astrojs/starlight/components/Code.astro';
import exampleCode from '../../../examples/demo.js?raw';
\<Code code={exampleCode} lang="js" title="demo.js" /\>
常见问题
Q: 如何添加 Google Analytics?
// astro.config.mjs
export default defineConfig({
integrations: [
starlight({
head: [
{
tag: 'script',
attrs: {
src: 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX',
async: true,
},
},
{
tag: 'script',
content: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
`,
},
],
}),
],
});
Q: 如何自定义 404 页面?
创建 src/pages/404.astro:
---
import { NotFoundPage } from '@astrojs/starlight/components';
---
<NotFoundPage /\>
Q: 如何添加版本切换器?
使用 Starlight 版本插件或自定义组件。
资源链接
- 官网: https://starlight.astro.build/
- GitHub: https://github.com/withastro/starlight
- Astro 文档: https://docs.astro.build/
- Discord 社区: https://astro.build/chat
- 示例网站: https://starlight.astro.build/showcase/
总结
Astro Starlight 是 2025 年最强大的文档框架之一,具有:
✅ 极致性能 - 零 JS 默认,加载速度最快 ✅ 框架无关 - 支持 React、Vue、Svelte 等混用 ✅ 开箱即用 - 搜索、国际化、暗黑模式全包含 ✅ 高度可定制 - 从样式到组件完全可控 ✅ 现代化架构 - Islands Architecture,按需加载
适合需要极致性能和高度灵活的文档项目!
最后更新:2025-11-08