Docusaurus 学习笔记
目录
简介
什么是 Docusaurus?
Docusaurus 是 Facebook(Meta)开源的一款静态网站生成器,专门用于构建文档网站和技术博客。
主要特点
- 📝 专注文档: 为技术文档优化的 Markdown 编写体验
- ⚛️ React 驱动: 使用 React 构建,可扩展性强
- 🌍 国际化: 内置多语言支持
- 🔍 搜索功能: 集成 Algolia DocSearch
- 📱 响应式设计: 移动端友好
- ⚡ 性能优秀: 预渲染静态 HTML,支持 PWA
- 🎨 可定制: 丰富的主题和插件系统
安装与初始化
环境要求
- Node.js 版本 >= 18.0
- npm / yarn / pnpm
快速开始
# 使用 npx 创建项目
npx create-docusaurus@latest my-website classic
# 或使用 npm
npm init docusaurus@latest my-website classic
# 或使用 yarn
yarn create docusaurus my-website classic
# 或使用 pnpm
pnpm create docusaurus my-website classic
启动开发服务器
cd my-website
npm start
访问 http://localhost:3000 查看网站。
项目结构
my-website/
├── blog/ # 博客文章目录
│ ├── 2021-08-26-welcome/
│ │ └── index.md
│ └── 2021-08-01-mdx.md
├── docs/ # 文档目录
│ ├── intro.md
│ └── tutorial-basics/
├── src/ # React 组件和页面
│ ├── components/ # 自定义组件
│ ├── css/ # 全局样式
│ └── pages/ # 自定义页面
│ └── index.js # 首页
├── static/ # 静态资源
│ └── img/ # 图片资源
├── docusaurus.config.js # 主配置文件
├── sidebars.js # 侧边栏配置
├── package.json
└── babel.config.js
关键目录说明
docs/: 存放所有文档 Markdown 文件blog/: 存放博客文章src/pages/: 自定义页面,支持 React 和 MDXstatic/: 静态资源,直接复制到构建输出docusaurus.config.js: 网站的核心配置
配置文件
docusaurus.config.js
这是 Docusaurus 的核心配置文件。
// @ts-check
const {themes} = require('prism-react-renderer');
/** @type {import('@docusaurus/types').Config} */
const config = {
// 基本信息
title: '我的网站',
tagline: '网站标语',
favicon: 'img/favicon.ico',
// 网站 URL
url: 'https://your-docusaurus-site.example.com',
baseUrl: '/',
// GitHub Pages 部署配置
organizationName: 'your-org', // GitHub 用户名/组织名
projectName: 'your-repo', // 仓库名
// 国际化配置
i18n: {
defaultLocale: 'zh-CN',
locales: ['zh-CN', 'en'],
},
// 预设配置
presets: [
[
'classic',
/** @type {import('@docusaurus/preset-classic').Options} */
({
docs: {
sidebarPath: './sidebars.js',
editUrl: 'https://github.com/your-org/your-repo/tree/main/',
},
blog: {
showReadingTime: true,
editUrl: 'https://github.com/your-org/your-repo/tree/main/',
},
theme: {
customCss: './src/css/custom.css',
},
}),
],
],
// 主题配置
themeConfig:
/** @type {import('@docusaurus/preset-classic').ThemeConfig} */
({
// 网站元数据
image: 'img/docusaurus-social-card.jpg',
// 导航栏
navbar: {
title: '我的网站',
logo: {
alt: 'Logo',
src: 'img/logo.svg',
},
items: [
{
type: 'docSidebar',
sidebarId: 'tutorialSidebar',
position: 'left',
label: '文档',
},
{to: '/blog', label: '博客', position: 'left'},
{
href: 'https://github.com/your-org/your-repo',
label: 'GitHub',
position: 'right',
},
],
},
// 页脚
footer: {
style: 'dark',
links: [
{
title: '文档',
items: [
{
label: '教程',
to: '/docs/intro',
},
],
},
{
title: '社区',
items: [
{
label: 'Stack Overflow',
href: 'https://stackoverflow.com/questions/tagged/docusaurus',
},
],
},
],
copyright: `Copyright © ${new Date().getFullYear()} My Project.`,
},
// 代码高亮主题
prism: {
theme: themes.github,
darkTheme: themes.dracula,
},
}),
};
module.exports = config;
sidebars.js
配置文档侧边栏结构。
/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */
const sidebars = {
// 自动生成侧边栏
tutorialSidebar: [
{
type: 'autogenerated',
dirName: '.',
},
],
// 或手动配置
manuallySidebar: [
'intro',
{
type: 'category',
label: '教程',
items: ['tutorial-basics/create-a-page', 'tutorial-basics/create-a-document'],
},
],
};
module.exports = sidebars;
文档编写
Markdown 基础
Docusaurus 支持标准 Markdown 和扩展语法。
Front Matter
每个文档文件顶部可以添加元数据:
---
id: my-doc-id
title: 我的文档标题
sidebar_label: 侧边栏显示的标题
sidebar_position: 1
description: 文档描述
keywords: [关键词1, 关键词2]
tags: [标签1, 标签2]
---
# 文档内容开始
MDX 支持
Docusaurus 支持 MDX,可以在 Markdown 中使用 React 组件。
---
title: MDX 示例
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
# 使用 React 组件
<Tabs>
<TabItem value="apple" label="苹果" default>
这是关于苹果的内容。
</TabItem>
<TabItem value="orange" label="橙子">
这是关于橙子的内容。
</TabItem>
</Tabs>
内置组件
1. 警告框(Admonitions)
:::note
这是一个提示。
:::
:::tip
这是一个技巧。
:::
:::info
这是一个信息。
:::
:::caution
这是一个警告。
:::
:::danger
这是一个危险提示。
:::
2. 代码块
```javascript title="example.js" showLineNumbers
function hello() {
console.log('Hello World!');
}
```
```jsx {1,4-6} title="src/components/HelloWorld.js"
import React from 'react';
function HelloWorld() {
// 高亮这些行
return <div>
<h1>Hello World!</h1>
</div>;
}
```
3. 选项卡(Tabs)
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs>
<TabItem value="js" label="JavaScript">
```js
console.log('Hello');
```
</TabItem>
<TabItem value="py" label="Python">
```python
print('Hello')
```
</TabItem>
</Tabs>
文档版本控制
# 创建新版本
npm run docusaurus docs:version 1.0.0
这会创建 versioned_docs/version-1.0.0/ 目录。
博客功能
博客文章结构
---
slug: welcome
title: 欢迎
authors: [slorber, yangshun]
tags: [hello, docusaurus]
---
# 欢迎使用博客
这是博客正文内容。
<!--truncate-->
这部分内容在列表页不会显示,只有点击"阅读更多"后才能看到。
作者信息
在 blog/authors.yml 中定义作者:
slorber:
name: Sébastien Lorber
title: Docusaurus 维护者
url: https://sebastienlorber.com
image_url: https://github.com/slorber.png
yangshun:
name: Yangshun Tay
title: Front End Engineer @ Facebook
url: https://github.com/yangshun
image_url: https://github.com/yangshun.png
博客配置
// docusaurus.config.js
blog: {
showReadingTime: true, // 显示阅读时间
blogTitle: '博客',
blogDescription: '我的技术博客',
postsPerPage: 10, // 每页文章数
blogSidebarTitle: '最近文章',
blogSidebarCount: 5, // 侧边栏显示的文章数
}
主题配置
颜色模式
// docusaurus.config.js
themeConfig: {
colorMode: {
defaultMode: 'light',
disableSwitch: false,
respectPrefersColorScheme: true,
},
}
自定义 CSS
在 src/css/custom.css 中自定义样式:
:root {
--ifm-color-primary: #2e8555;
--ifm-color-primary-dark: #29784c;
--ifm-color-primary-darker: #277148;
--ifm-color-primary-darkest: #205d3b;
--ifm-color-primary-light: #33925d;
--ifm-color-primary-lighter: #359962;
--ifm-color-primary-lightest: #3cad6e;
--ifm-code-font-size: 95%;
--docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1);
}
[data-theme='dark'] {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: #21af90;
--ifm-color-primary-darker: #1fa588;
--ifm-color-primary-darkest: #1a8870;
--ifm-color-primary-light: #29d5b0;
--ifm-color-primary-lighter: #32d8b4;
--ifm-color-primary-lightest: #4fddbf;
--docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.3);
}
自定义组件
可以通过 Swizzling 自定义主题组件:
# 查看可自定义的组件
npm run swizzle @docusaurus/theme-classic -- --list
# Eject 一个组件(完全自定义)
npm run swizzle @docusaurus/theme-classic Footer -- --eject
# Wrap 一个组件(包装增强)
npm run swizzle @docusaurus/theme-classic Footer -- --wrap
插件系统
常用官方插件
1. 内容插件
// docusaurus.config.js
plugins: [
[
'@docusaurus/plugin-content-docs',
{
id: 'community',
path: 'community',
routeBasePath: 'community',
sidebarPath: require.resolve('./sidebarsCommunity.js'),
},
],
]
2. PWA 插件
npm install @docusaurus/plugin-pwa
plugins: [
[
'@docusaurus/plugin-pwa',
{
debug: true,
offlineModeActivationStrategies: [
'appInstalled',
'standalone',
'queryString',
],
pwaHead: [
{
tagName: 'link',
rel: 'icon',
href: '/img/logo.png',
},
{
tagName: 'link',
rel: 'manifest',
href: '/manifest.json',
},
],
},
],
]
3. 搜索插件
使用 Algolia DocSearch:
themeConfig: {
algolia: {
appId: 'YOUR_APP_ID',
apiKey: 'YOUR_SEARCH_API_KEY',
indexName: 'YOUR_INDEX_NAME',
contextualSearch: true,
},
}
第三方插件
docusaurus-plugin-sass: SASS 支持@docusaurus/plugin-google-analytics: Google Analytics@docusaurus/plugin-google-gtag: Google Tag Managerdocusaurus-plugin-image-zoom: 图片缩放
部署
构建生产版本
npm run build
构建产物在 build/ 目录中。
部署到 GitHub Pages
配置
// docusaurus.config.js
module.exports = {
url: 'https://username.github.io',
baseUrl: '/project-name/',
organizationName: 'username',
projectName: 'project-name',
deploymentBranch: 'gh-pages',
trailingSlash: false,
};
部署命令
# 使用 SSH
USE_SSH=true npm run deploy
# 使用 HTTPS
GIT_USER=<your-username> npm run deploy
部署到 Vercel
- 导入 GitHub 仓库到 Vercel
- Vercel 会自动检测 Docusaurus 项目
- 点击部署即可
部署到 Netlify
- 连接 GitHub 仓库
- 构建命令:
npm run build - 发布目录:
build - 点击部署
部署到 Cloudflare Pages
# 构建命令
npm run build
# 输出目录
build
高级特性
国际化(i18n)
配置多语言
// docusaurus.config.js
module.exports = {
i18n: {
defaultLocale: 'zh-CN',
locales: ['zh-CN', 'en', 'ja'],
localeConfigs: {
en: {
label: 'English',
direction: 'ltr',
},
'zh-CN': {
label: '简体中文',
direction: 'ltr',
},
},
},
};
翻译文件结构
i18n/
├── en/
│ ├── docusaurus-plugin-content-docs/
│ │ └── current/
│ │ └── intro.md
│ ├── docusaurus-plugin-content-blog/
│ └── docusaurus-theme-classic/
└── ja/
└── ...
翻译命令
# 写入默认语言翻译
npm run write-translations -- --locale zh-CN
# 启动特定语言的开发服务器
npm run start -- --locale en
SEO 优化
// 在页面或文档中
export const Head = () => (
<>
<meta property="og:title" content="我的页面标题" />
<meta property="og:description" content="页面描述" />
<meta property="og:image" content="/img/social-card.png" />
</>
);
自定义页面
在 src/pages/ 创建 React 组件:
// src/pages/my-page.js
import React from 'react';
import Layout from '@theme/Layout';
export default function MyPage() {
return (
<Layout title="我的页面" description="页面描述">
<div style={{padding: '2rem'}}>
<h1>自定义页面</h1>
<p>这是一个完全自定义的页面。</p>
</div>
</Layout>
);
}
访问 http://localhost:3000/my-page
静态资源处理
// 引用静态资源
import useBaseUrl from '@docusaurus/useBaseUrl';
function MyComponent() {
return <img src={useBaseUrl('/img/logo.png')} alt="Logo" />;
}
环境变量
// docusaurus.config.js
module.exports = {
customFields: {
apiUrl: process.env.API_URL,
},
};
// 在组件中使用
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
function MyComponent() {
const {siteConfig} = useDocusaurusContext();
const apiUrl = siteConfig.customFields.apiUrl;
}
最佳实践
1. 文档组织
- 使用清晰的目录结构
- 合理使用
sidebar_position控制顺序 - 使用类别分组相关文档
- 提供清晰的文档 ID 和标题
2. Markdown 编写
- 使用 Front Matter 提供元数据
- 合理使用标题层级
- 使用警告框突出重要信息
- 为代码块添加语言标识和标题
- 使用
<!--truncate-->控制博客摘要
3. 性能优化
- 优化图片大小和格式
- 使用 SVG 作为图标
- 启用代码分割
- 配置 PWA 离线访问
4. 用户体验
- 提供搜索功能
- 配置导航栏和页脚
- 支持深色模式
- 添加"编辑此页"链接
- 显示阅读时间
5. 维护建议
- 定期更新 Docusaurus 版本
- 使用版本控制管理文档
- 配置 CI/CD 自动部署
- 定期检查链接有效性
常用命令总结
# 开发
npm start # 启动开发服务器
npm start -- --host 0.0.0.0 # 允许外部访问
npm start -- --locale en # 启动特定语言
# 构建
npm run build # 构建生产版本
npm run serve # 本地预览构建结果
# 部署
npm run deploy # 部署到 GitHub Pages
# 文档版本
npm run docusaurus docs:version 1.0.0 # 创建版本
# 清理
npm run clear # 清理缓存
npm run docusaurus clear # 清理生成的文件
# Swizzling
npm run swizzle # 交互式选择组件
npm run swizzle -- --list # 列出可自定义组件
# 国际化
npm run write-translations # 提取翻译文本
npm run write-heading-ids # 生成标题 ID
常见问题
1. 端口已被占用
# 使用不同端口
npm start -- --port 3001
2. 清除缓存
npm run clear
rm -rf .docusaurus
rm -rf build
3. 图片不显示
- 确保图片在
static/目录 - 使用
useBaseUrlHook - 检查路径大小写
4. 部署后样式丢失
检查 baseUrl 配置是否正确。
5. Markdown 不生效
确保文件扩展名为 .md 或 .mdx。
学习资源
官方资源
- 官方网站: https://docusaurus.io/
- GitHub: https://github.com/facebook/docusaurus
- 社区: https://discord.gg/docusaurus
示例项目
- React 文档: https://react.dev/
- Jest 文档: https://jestjs.io/
- Prettier 文档: https://prettier.io/
相关工具
- MDX: https://mdxjs.com/
- Prism: https://prismjs.com/
- Algolia DocSearch: https://docsearch.algolia.com/
总结
Docusaurus 是一个功能强大、易于使用的文档网站生成器。主要优势:
✅ 开箱即用,快速搭建
✅ Markdown/MDX 编写体验优秀
✅ React 生态,可扩展性强
✅ 内置国际化、搜索、版本控制
✅ 部署简单,支持多平台
✅ 社区活跃,文档完善
适合构建:
- 技术文档网站
- 项目文档
- 个人技术博客
- 知识库系统
- 开源项目文档
开始使用 Docusaurus,让你的文档更专业! 🚀