跳到主要内容

核心知识点

0. 相关文档

好的,作为一名前端专家,我为你详细梳理 Docusaurus 的核心知识点,包含大纲、文字说明和代码示例,并以 Markdown 格式呈现。

Docusaurus 是一个由 Facebook(现 Meta)开源的静态站点生成器,专门用于构建优化的文档网站。它使用 React 构建,易于安装和使用,并提供了许多开箱即用的功能,如版本控制、国际化、搜索等。

1. 初始化与项目结构

说明

使用官方提供的脚手架可以快速创建一个新的 Docusaurus 站点。了解其基本的项目结构对于后续的开发和维护至关重要。

  • npx create-docusaurus@latest my-website [classic|facebook|@org/preset-name]: 初始化命令。classic 是最常用的模板。
  • /blog/: 存放博客文章(Markdown 文件)。
  • /docs/: 存放文档页面(Markdown 文件)。
  • /src/: 存放自定义 React 组件和页面。
    • /src/pages/**: 存放非文档/博客的独立页面(.js, .jsx, .ts, .tsx, .md, .mdx)。
    • /src/components/**: 存放共享的 React 组件。
    • /src/css/**: 存放全局 CSS 样式文件(如 custom.css)。
  • /static/: 存放静态资源(图片、.htaccess 等),构建时会直接复制到输出目录的根路径。
  • docusaurus.config.js: 核心配置文件,用于配置站点元数据、主题、插件、导航栏、页脚等。
  • sidebars.js: (或 sidebars.json) 用于配置文档侧边栏的结构。
  • babel.config.js: Babel 配置文件。
  • package.json: 项目依赖和脚本。

示例代码 (初始化命令)

# 使用 classic 模板初始化一个名为 my-website 的站点
npx create-docusaurus@latest my-website classic

# 进入项目目录
cd my-website

# 启动开发服务器
npm run start
# 或者 yarn start

# 构建静态站点
npm run build
# 或者 yarn build

2. 配置文件 (docusaurus.config.js)

说明

这是 Docusaurus 站点的中央枢纽,几乎所有的全局设置都在这里完成。

  • title: 网站标题。
  • tagline: 网站标语。
  • url: 站点的部署 URL。
  • baseUrl: 站点的基础路径(如果部署在子目录下,例如 /my-docs/)。
  • onBrokenLinks, onBrokenMarkdownLinks: 如何处理无效链接。
  • favicon: 网站图标路径。
  • organizationName, projectName: 通常是 GitHub 的组织名和仓库名,用于部署和链接。
  • presets: 预设是插件和主题的集合,@docusaurus/preset-classic 是最常用的。
  • themeConfig: 用于配置主题(尤其是 classic 主题)的选项,如导航栏、页脚、颜色模式、Prism 代码高亮主题、Algolia 搜索等。
  • plugins: 配置额外的插件。
  • themes: 配置额外的主题或主题组件。
  • i18n: 配置国际化选项(见后续章节)。

示例代码 (docusaurus.config.js 结构)

// docusaurus.config.js
// @ts-check
const lightCodeTheme = require("prism-react-renderer/themes/github");
const darkCodeTheme = require("prism-react-renderer/themes/dracula");

/** @type {import('@docusaurus/types').Config} */
const config = {
title: "My Awesome Site",
tagline: "Dinosaurs are cool",
url: "https://your-docusaurus-test-site.com",
baseUrl: "/", // Use '/my-project/' if deployed to a subdirectory
onBrokenLinks: "throw",
onBrokenMarkdownLinks: "warn",
favicon: "img/favicon.ico",

// GitHub pages deployment config.
organizationName: "your-org",
projectName: "your-repo",

i18n: {
// Internationalization config (example)
defaultLocale: "en",
locales: ["en", "zh-Hans"],
},

presets: [
[
"classic",
/** @type {import('@docusaurus/preset-classic').Options} */
({
docs: {
// Docs plugin options
sidebarPath: require.resolve("./sidebars.js"),
// Point to the edit URL (e.g., GitHub repo)
editUrl: "https://github.com/your-org/your-repo/tree/main/",
routeBasePath: "/docs", // Serve docs at the /docs route
// ... other docs options (versioning, etc.)
},
blog: {
// Blog plugin options
showReadingTime: true,
editUrl: "https://github.com/your-org/your-repo/tree/main/",
// ... other blog options
},
theme: {
// Theme options
customCss: require.resolve("./src/css/custom.css"),
},
}),
],
],

themeConfig:
/** @type {import('@docusaurus/preset-classic').ThemeConfig} */
({
navbar: {
// Navbar configuration
title: "My Site",
logo: {
alt: "My Site Logo",
src: "img/logo.svg",
},
items: [
{
type: "doc", // Links to a doc
docId: "intro", // The ID of the starting doc
position: "left",
label: "Tutorial",
},
{ to: "/blog", label: "Blog", position: "left" }, // Links to the blog
{
// Example: Dropdown
label: "Community",
position: "left",
items: [
{ label: "Stack Overflow", href: "..." },
{ label: "Discord", href: "..." },
],
},
{
// Links to GitHub repo
href: "https://github.com/your-org/your-repo",
label: "GitHub",
position: "right",
},
{
// Locale dropdown (if i18n is enabled)
type: "localeDropdown",
position: "right",
},
],
},
footer: {
// Footer configuration
style: "dark",
links: [
/* ... footer links structure ... */
],
copyright: `Copyright © ${new Date().getFullYear()} My Project, Inc. Built with Docusaurus.`,
},
prism: {
// Code block theming
theme: lightCodeTheme,
darkTheme: darkCodeTheme,
additionalLanguages: ["java", "php"], // Add more languages if needed
},
// Algolia DocSearch config (example)
// algolia: {
// appId: 'YOUR_APP_ID',
// apiKey: 'YOUR_SEARCH_API_KEY',
// indexName: 'YOUR_INDEX_NAME',
// contextualSearch: true,
// },
colorMode: {
// Dark/Light mode config
defaultMode: "light",
disableSwitch: false,
respectPrefersColorScheme: true,
},
}),

// plugins: [ /* ... custom plugins ... */ ],
};

module.exports = config;

3. 内容创建 - 文档 (Docs)

说明

文档是 Docusaurus 的核心功能,通常存放在 /docs 目录下。使用 Markdown (或 MDX) 编写。

  • 文件结构映射侧边栏 (默认行为): 如果不使用 sidebars.js,文件结构会自动生成侧边栏。
  • sidebars.js: 提供对侧边栏结构、顺序和层级的完全控制。可以定义多个侧边栏。
  • Front Matter: Markdown 文件顶部的 YAML 或 TOML 块,用于定义元数据。
    • id: 文档的唯一 ID (默认为文件名,不含扩展名)。
    • title: 文档标题 (会覆盖 Markdown 的 H1 标题)。
    • sidebar_label: 在侧边栏显示的标签 (默认为标题)。
    • sidebar_position: 控制文档在侧边栏分类中的顺序 (数字越小越靠前)。
    • slug: 自定义文档的 URL 路径 (相对于 /docs 基础路径)。
    • tags: 添加标签。
    • hide_table_of_contents: 隐藏右侧的页面内目录。
  • 路由: 文档路由通常是 /docs/[目录结构]/[id]/docs/[slug]

示例代码

文档文件 (/docs/tutorial-basics/create-a-page.md)

---
id: create-a-page # Optional: defaults to 'create-a-page'
title: Creating Your First Page # Overrides the H1 below if present
sidebar_label: Create a Page # Label shown in the sidebar
sidebar_position: 1 # First item in its category
slug: /getting-started/first-page # Custom URL: /docs/getting-started/first-page
tags: [beginner, tutorial]
---

# Creating Your First Page (This H1 might be overridden by front matter title)

Welcome to your first Docusaurus page!

You can write content using **Markdown**.

## Sub-heading

More details here...

```js title="Example Code Snippet" showLineNumbers {1, 3-4}
function greet(name) {
// Highlight line 1 and lines 3-4
const message = `Hello, ${name}!`;
console.log(message);
return message;
}
```

侧边栏配置 (sidebars.js)

// sidebars.js
/**
* Creating a sidebar enables you to:
- create an ordered group of docs
- render a sidebar for each doc of that group
- provide next/previous navigation

The sidebars can be generated from the filesystem, or explicitly defined here.

Create as many sidebars as you want.
*/

/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */
const sidebars = {
// By default, Docusaurus generates a sidebar from the docs folder structure
// tutorialSidebar: [{type: 'autogenerated', dirName: '.'}],

// Example: Explicitly defined sidebar
tutorialSidebar: [
// Section Header (unlinked)
{
type: "html",
value: '<span class="sidebar-divider">Basics</span>',
defaultStyle: true,
},
// Link to a specific doc
"intro", // Assuming docs/intro.md exists
{
type: "category", // Collapsible category
label: "Tutorial Basics",
link: {
// Optional: Make category label clickable
type: "generated-index", // Generates an index page
title: "Tutorial Basics Overview",
description: "Learn the basics of Docusaurus!",
slug: "/category/tutorial-basics",
},
items: [
"tutorial-basics/create-a-page", // Refers to docs/tutorial-basics/create-a-page.md (by ID or path)
"tutorial-basics/create-a-document",
// Sub-category
{
type: "category",
label: "Advanced",
items: ["tutorial-basics/markdown-features"],
},
],
},
// Another top-level category
{
type: "category",
label: "Guides",
items: ["guides/deployment", "guides/theming"],
},
],

// Example: Another sidebar for a different section (e.g., API)
// apiSidebar: [
// {
// type: 'autogenerated',
// dirName: 'api', // Assuming docs/api directory exists
// },
// ],
};

module.exports = sidebars;

4. 内容创建 - 博客 (Blog)

说明

Docusaurus 包含一个内置的博客插件,用于发布文章、新闻等。

  • 存放位置: /blog 目录。
  • 文件名格式: 推荐 YYYY-MM-DD-your-post-title.md (或 .mdx)。日期用于排序。
  • Front Matter:
    • title: 博客文章标题。
    • author: 作者名字。
    • author_title: 作者头衔。
    • author_url: 指向作者信息的链接(如 GitHub, Twitter)。
    • author_image_url: 作者头像 URL。
    • tags: 标签列表。
    • slug: 自定义 URL slug。
    • date: (可选) 覆盖文件名中的日期。
    • hide_table_of_contents: 隐藏目录。
  • 摘要: 使用 <!--truncate--> 分隔符来指定在博客列表页显示的摘要内容。
  • 路由: 博客列表页通常在 /blog,文章页在 /blog/[slug]/blog/YYYY/MM/DD/[slug] (取决于配置)。

示例代码 (/blog/2023-10-27-welcome/index.md)

---
slug: welcome-to-our-blog
title: Welcome to the New Blog!
authors: [john_doe] # Reference an author defined in authors.yml or inline
tags: [announcement, docusaurus]
date: 2023-10-27 # Optional, overrides filename date if needed
# You can also define authors inline:
# authors:
# - name: John Doe
# title: Core Maintainer
# url: https://github.com/johndoe
# image_url: https://github.com/johndoe.png
---

This is our first blog post using Docusaurus! We are excited to share updates here.

<!--truncate-->

Here is the rest of the content, which will only appear on the blog post page itself, not in the list preview.

We plan to cover topics like:

- Feature releases
- Tutorials
- Community updates

Stay tuned!

作者配置 (authors.yml - 可选, 放在项目根目录)

# authors.yml
john_doe:
name: John Doe
title: Core Maintainer
url: https://github.com/johndoe
image_url: https://github.com/johndoe.png

jane_smith:
name: Jane Smith
title: Documentation Lead
url: https://twitter.com/janesmith
image_url: /img/jane-avatar.jpg # Path relative to static folder

5. 内容创建 - 页面 (Pages)

说明

用于创建不属于文档或博客结构的独立页面,例如首页、产品特性展示页、联系页面等。

  • 存放位置: /src/pages/ 目录。
  • 文件类型: 可以是 React 组件 (.js, .jsx, .ts, .tsx) 或 Markdown (.md, .mdx) 文件。
  • 路由: 基于 /src/pages/ 下的文件路径自动生成。
    • /src/pages/index.js -> /
    • /src/pages/contact.js -> /contact
    • /src/pages/about/team.md -> /about/team
  • React 页面: 提供完全的 React 能力,可以自由构建 UI、获取数据、使用状态等。通常会导入 @theme/Layout 来获得标准的页眉、页脚和样式。
  • Markdown 页面: 渲染方式类似文档页面,但不包含侧边栏或“上一页/下一页”导航。

示例代码

React 页面 (/src/pages/hello.js)

import React from "react";
import Layout from "@theme/Layout"; // Import the standard layout

export default function HelloPage() {
return (
<Layout title="Hello" description="A custom React page in Docusaurus">
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "50vh",
fontSize: "20px",
}}
>
<h1>Hello from a Custom React Page!</h1>
<p>
This page is created using a React component inside{" "}
<code>/src/pages/</code>.
</p>
{/* You can add any React components or logic here */}
</div>
</Layout>
);
}

Markdown 页面 (/src/pages/privacy-policy.md)

---
title: Privacy Policy
# No sidebar options needed here
---

# Our Privacy Policy

Last updated: October 27, 2023

This page informs you of our policies regarding the collection, use, and disclosure of personal data when you use our Service and the choices you have associated with that data.

... (rest of the policy content) ...

6. Markdown 特性 & MDX

说明

Docusaurus 扩展了标准 Markdown 功能,并完全支持 MDX,允许在 Markdown 文件中嵌入和使用 React 组件。

  • Front Matter: (已在 Docs/Blog 部分介绍)。

  • Admonitions (提示、警告等): 使用特定语法创建醒目的信息框。

    :::note
    This is a note.
    :::

    :::tip
    Here's a helpful tip.
    :::

    :::info
    Some information.
    :::

    :::caution
    Be careful with this action.
    :::

    :::danger
    This action is dangerous or indicates an error.
    :::
  • Code Blocks:

    • 语法高亮 (通过 Prism React Renderer)。
    • 行高亮 ({N, M-P} 语法)。
    • 行号 (showLineNumbers 标志)。
    • 标题 (title="..." 属性)。
  • Tabs: 在内容中创建标签页切换。

    import Tabs from '@theme/Tabs';
    import TabItem from '@theme/TabItem';

    <Tabs groupId="operating-systems">
    <TabItem value="mac" label="macOS">
    macOS instructions...
    </TabItem>
    <TabItem value="win" label="Windows">
    Windows instructions...
    </TabItem>
    <TabItem value="linux" label="Linux">
    Linux instructions...
    </TabItem>
    </Tabs>
  • MDX:

    • 在 Markdown 中 importexport JavaScript/React 组件。
    • 直接在 Markdown 中使用 JSX 语法渲染组件。
    • 可以将 Markdown 内容传递给组件的 children prop。

示例代码 (MDX)

/docs/using-mdx.mdx
---
title: Using MDX in Docusaurus
---

import MyCustomButton from "@site/src/components/MyCustomButton"; // Import custom component
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";

# MDX = Markdown + JSX

MDX allows you to use React components directly in your Markdown files.

This is **standard Markdown**.

## Using a Custom Component

Here's a button imported from our `src/components` directory:

<MyCustomButton onClick={() => alert("Button Clicked!")}>
Click Me!
</MyCustomButton>

## Using Built-in Theme Components

Docusaurus provides theme components like Tabs:

<Tabs>
<TabItem value="js" label="JavaScript">

```js
console.log("Hello from JS tab!");
```

</TabItem>
<TabItem value="py" label="Python">

```python
print("Hello from Python tab!")
```

</TabItem>
</Tabs>

对应组件 (/src/components/MyCustomButton.js)

// src/components/MyCustomButton.js
import React from "react";
import styles from "./MyCustomButton.module.css"; // Example using CSS Modules

export default function MyCustomButton({ children, onClick }) {
return (
<button className={styles.myButton} onClick={onClick}>
{children}
</button>
);
}

// src/components/MyCustomButton.module.css
// .myButton {
// background-color: tomato;
// color: white;
// padding: 8px 16px;
// border: none;
// border-radius: 5px;
// cursor: pointer;
// font-size: 1rem;
// }
// .myButton:hover {
// background-color: crimson;
// }

Inline JSX

你甚至可以使用内联 JSX 来进行简单的样式设置或添加元素:

This text is <span style={{ color: 'rebeccapurple', fontWeight: 'bold' }}>styled with inline JSX</span>.

export const Highlight = (
{ children, color } // Define a simple component right here
) => (
<span style={{ backgroundColor: color, padding: "0.2rem" }}>{children}</span>
);

This is <Highlight color="yellow">highlighted text</Highlight> using an exported component.

说明

导航元素帮助用户浏览站点。它们主要在 docusaurus.config.jsthemeConfig 部分进行配置。

  • Navbar (导航栏): 顶部的导航栏。可以包含 Logo、站点标题、文档链接、博客链接、外部链接、自定义链接、搜索框、明暗模式切换、语言切换下拉菜单等。配置见 themeConfig.navbar
  • Sidebar (侧边栏): 主要用于文档部分,提供文档结构导航。通过 sidebars.js (或自动生成) 定义。配置见 presets.docs.sidebarPathsidebars.js 文件本身。
  • Footer (页脚): 页面底部的区域。可以包含版权信息、链接列、Logo、自定义 HTML 等。配置见 themeConfig.footer

示例代码 (已在 docusaurus.config.jssidebars.js 示例中展示)

8. 样式与主题化 (Styling & Theming)

说明

Docusaurus 允许你自定义站点的外观。

  • src/css/custom.css: 默认的全局 CSS 文件,可以在这里覆盖 Docusaurus 的默认样式或添加自定义样式。该文件路径在 docusaurus.config.jstheme.customCss 中指定。
  • Infima CSS 变量: classic 主题基于 Infima CSS 框架。可以通过覆盖 Infima 的 CSS 变量来快速调整颜色、字体、间距等。这些变量通常在 custom.css:root[data-theme='dark'] 选择器中定义。
  • CSS Modules: 对于自定义 React 组件,推荐使用 CSS Modules (.module.css) 来实现局部作用域样式。
  • Swizzling: 更高级的定制方式(见下一节)。

示例代码 (src/css/custom.css)

/* src/css/custom.css */

/**
* Any CSS placed here will be imported globally.
*/

/* Example: Change primary color using Infima CSS variables */
:root {
--ifm-color-primary: #25c2a0; /* New primary color for light mode */
--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;
--ifm-code-font-size: 95%; /* Slightly smaller code font size */
--docusaurus-highlighted-code-line-bg: rgba(
0,
0,
0,
0.1
); /* Light mode line highlight */
}

/* Example: Dark mode overrides */
[data-theme="dark"] {
--ifm-color-primary: #25c2a0; /* Same primary color for dark mode */
--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
); /* Dark mode line highlight */
}

/* Example: Custom global style */
.my-global-class {
border: 1px dashed var(--ifm-color-primary);
padding: 1rem;
margin: 1rem 0;
}

9. Swizzling

说明

Swizzling 是 Docusaurus 提供的一种高级定制机制,允许你替换包装主题提供的 React 组件。当你需要对某个组件进行深度修改,而不仅仅是 CSS 调整时,可以使用 Swizzling。

  • 命令: npm run swizzle [themeName] [ComponentName] [-- --eject|--wrap]
    • --eject: 将原始组件代码复制到你的 src/theme 目录下,你可以完全修改它。注意: 这会使你脱离主题的更新,需要手动维护。
    • --wrap: 创建一个包装组件,你可以在其中导入并渲染原始组件,并在其前后添加逻辑或元素。这是推荐的方式,因为它更容易维护和升级。
  • 目标目录: Swizzled 组件会被放在 src/theme/ 目录下,保持与原始主题相同的结构。

示例代码 (命令行)

# 查看可 swizzle 的组件
npm run swizzle @docusaurus/theme-classic --list

# Wrap (推荐): 包装 Footer 组件以添加额外内容
npm run swizzle @docusaurus/theme-classic Footer -- --wrap

# Eject (谨慎使用): 完全替换 DocItem 组件
# npm run swizzle @docusaurus/theme-classic DocItem -- --eject

示例包装组件 (src/theme/Footer/index.js - wrap 后生成)

// src/theme/Footer/index.js
import React from "react";
import Footer from "@theme-original/Footer"; // Import the original component
import type FooterType from "@theme/Footer";
import type { WrapperProps } from "@docusaurus/types";

type Props = WrapperProps<typeof FooterType>;

export default function FooterWrapper(props: Props): JSX.Element {
return (
<>
{/* You can add custom content before the original Footer */}
<div
style={{ textAlign: "center", padding: "10px", background: "#f0f0f0" }}
>
My Custom Content Before Footer
</div>

{/* Render the original Footer */}
<Footer {...props} />

{/* You can add custom content after the original Footer */}
{/* <div style={{ textAlign: 'center', padding: '5px', background: '#e0e0e0' }}>
Extra Info After Footer
</div> */}
</>
);
}

10. 插件 (Plugins)

说明

插件用于为 Docusaurus 站点添加或修改功能。Docusaurus 本身的核心功能(如文档、博客、页面)就是通过插件实现的。

  • 官方插件:@docusaurus/plugin-content-docs, @docusaurus/plugin-content-blog, @docusaurus/plugin-content-pages, @docusaurus/plugin-sitemap 等,通常包含在 preset-classic 中。
  • 社区插件: 许多由社区开发的插件可用于添加特定功能。
  • 自定义插件: 你可以创建自己的本地插件来封装站点特定的逻辑。
  • 配置: 插件在 docusaurus.config.jsplugins 数组中配置,可以传递选项。

示例代码 (docusaurus.config.js 中配置插件)

// docusaurus.config.js
module.exports = {
// ... other config
plugins: [
// Example: Add a redirects plugin (install first: npm i @docusaurus/plugin-client-redirects)
[
"@docusaurus/plugin-client-redirects",
{
// Plugin options
redirects: [
{
to: "/docs/intro", // New path
from: ["/docs/old-intro", "/old-documentation"], // Old path(s)
},
],
// createRedirects(existingPath) { /* ... function for dynamic redirects ... */ },
},
],
// Example: Add a custom local plugin
// './plugins/my-custom-plugin', // Path to your local plugin directory or file
],
// Presets also implicitly add plugins
presets: [
/* ... preset config includes docs, blog, pages plugins ... */
],
};

11. 静态资源 (/static 目录)

说明

static 目录下的所有文件和文件夹会在构建时被直接复制到最终输出目录(build 目录)的根路径下。适合存放图片、字体文件、robots.txtCNAME、验证文件等不需要 Webpack 处理的资源。

示例代码 (使用 static 目录中的图片)

<!-- In a Markdown file (e.g., /docs/intro.md) -->

Referencing an image from the `static` folder:

![My Logo](/img/logo.svg) <!-- Assumes /static/img/logo.svg exists -->

<!-- Or use it in an <img> tag -->

<img src="/img/diagram.png" alt="Architecture Diagram" /> <!-- Assumes /static/img/diagram.png exists -->

12. 版本控制 (Docs Versioning)

说明

Docusaurus 支持为文档创建版本快照,允许用户浏览项目不同发布版本的文档。

  • 创建版本: 使用命令 npm run docusaurus docs:version [version_name] (例如 1.0.0)。
  • 文件结构:
    • /docs/ 始终包含下一个版本(或当前开发中)的文档。
    • /versioned_docs/version-[version_name]/ 包含特定版本的文档快照。
    • /versioned_sidebars/version-[version_name]-sidebars.json 包含特定版本的侧边栏快照。
    • /versions.json 文件(在项目根目录)列出所有可用版本。
  • 配置:docusaurus.config.jspresets.docs 选项中可以配置版本相关的行为,如 lastVersion(最新稳定版)、onlyIncludeCurrentVersion(仅构建当前开发版)等。
  • 导航: 启用版本控制后,导航栏通常会显示一个版本下拉菜单。

示例代码 (命令行)

# Create version 1.0.0 (copies current /docs content)
npm run docusaurus docs:version 1.0.0

# Create version 2.0.0 (copies current /docs content again)
npm run docusaurus docs:version 2.0.0

# Now /docs is for the *next* version (e.g., development)
# /versioned_docs/version-2.0.0/ contains the 2.0.0 docs
# /versioned_docs/version-1.0.0/ contains the 1.0.0 docs
# versions.json lists ["2.0.0", "1.0.0"]

# Delete a version
npm run docusaurus docs:version:delete 1.0.0

13. 国际化 (i18n)

说明

Docusaurus 提供完整的国际化 (i18n) 支持,允许你将站点翻译成多种语言。

  • 配置:docusaurus.config.jsi18n 对象中配置 defaultLocalelocales
  • 文件结构:
    • 基础(默认语言)内容在 /docs, /blog, /src/pages 等处。
    • 翻译内容放在项目根目录的 /i18n/[locale]/ 目录下,保持与原结构对应的路径。例如,docs/intro.md 的中文翻译是 /i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.md
    • JSON 翻译文件用于翻译主题组件(如导航栏标签、按钮文本等),位于 /i18n/[locale]/code.json 或主题/插件对应的 JSON 文件中。
  • 提取: 使用 npm run docusaurus write-translations 命令可以自动生成待翻译的 JSON 文件。
  • 导航: 启用 i18n 后,导航栏通常会显示一个语言切换下拉菜单(localeDropdown)。

示例代码 (docusaurus.config.js i18n 配置)

// docusaurus.config.js
module.exports = {
// ... other config
i18n: {
defaultLocale: "en", // Default language
locales: ["en", "zh-Hans", "fr"], // Supported languages
localeConfigs: {
// Optional: configure specifics per locale
en: {
label: "English",
direction: "ltr",
htmlLang: "en-US",
},
"zh-Hans": {
label: "简体中文", // Label for the dropdown
direction: "ltr",
htmlLang: "zh-Hans",
},
fr: {
label: "Français",
},
},
},
themeConfig: {
navbar: {
items: [
// ... other items
{
// Add locale dropdown
type: "localeDropdown",
position: "right",
},
],
},
},
};

示例翻译文件结构

my-website/
├── docs/
│ └── intro.md
├── blog/
│ └── 2023-01-01-post.md
├── i18n/
│ └── zh-Hans/ # Chinese locale folder
│ ├── code.json # UI translations (navbar, buttons etc.)
│ ├── docusaurus-plugin-content-blog/ # Blog translations
│ │ └── 2023-01-01-post.md
│ └── docusaurus-plugin-content-docs/ # Docs translations
│ └── current/ # 'current' for the current/next version
│ └── intro.md
│ └── fr/ # French locale folder
│ ├── code.json
│ └── ... (similar structure)
└── docusaurus.config.js

说明

Docusaurus 内建了对 Algolia DocSearch 的支持,这是目前推荐的搜索方案。需要申请 Algolia DocSearch 服务(对开源项目免费),然后在 docusaurus.config.js 中配置 themeConfig.algolia

示例代码 (docusaurus.config.js Algolia 配置)

// docusaurus.config.js
module.exports = {
// ... other config
themeConfig: {
// ... other themeConfig
algolia: {
// The application ID provided by Algolia
appId: "YOUR_APP_ID",

// Public API key: it is safe to commit it
apiKey: "YOUR_SEARCH_API_KEY",

indexName: "YOUR_INDEX_NAME",

// Optional: see doc section below
contextualSearch: true,

// Optional: Specify domains where the navigation should occur through window.location instead directly routing
// externalUrlRegex: 'external\\.com|domain\\.com',

// Optional: Algolia search parameters
// searchParameters: {},

// Optional: path for search page that enabled by default (`false` to disable)
searchPagePath: "search",

//... other Algolia params
},
},
};

15. 部署 (Deployment)

说明

Docusaurus 构建的是一个静态站点 (位于 build 目录),可以部署到任何静态文件托管服务。

  • 构建命令: npm run buildyarn build
  • 常见托管平台:
    • GitHub Pages (官方提供 deploy 命令支持)
    • Vercel (推荐,与 Next.js/Docusaurus 集成良好)
    • Netlify
    • AWS S3 + CloudFront
    • Azure Static Web Apps
    • 等等...
  • GitHub Pages 部署:
    1. docusaurus.config.js 中配置 organizationName, projectName, deploymentBranch (通常是 gh-pages) 以及 urlbaseUrl
    2. 安装 gh-pages 包: npm install --save-dev gh-pages
    3. package.json 中添加部署脚本: "deploy": "docusaurus deploy"
    4. 运行 GIT_USER=<YourGitHubUsername> npm run deploy (或使用 SSH keys)。

示例代码 (package.json 部署脚本)

{
"name": "my-website",
"version": "0.0.0",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy", // Deployment script
"clear": "docusaurus clear",
"serve": "docusaurus serve",
"write-translations": "docusaurus write-translations",
"write-heading-ids": "docusaurus write-heading-ids",
"typecheck": "tsc"
},
// ... dependencies
"devDependencies": {
"@docusaurus/module-type-aliases": "...",
// ... other devDependencies
"gh-pages": "^5.0.0" // Required for docusaurus deploy command
}
}