Skip to main content
Version: 3.5.1

升级到 Docusaurus v3

¥Upgrading to Docusaurus v3

本文档将帮助你将站点从 Docusaurus v2 升级到 Docusaurus v3。

¥This documentation will help you upgrade your site from Docusaurus v2 to Docusaurus v3.

Docusaurus v3 是一个新的主要版本,其中包括需要你相应调整站点的重大更改。我们将在此过程中进行指导,并提出一些可选建议。

¥Docusaurus v3 is a new major version, including breaking changes requiring you to adjust your site accordingly. We will guide to during this process, and also mention a few optional recommendations.

这不是完全重写,并且重大更改相对容易处理。最简单的站点最终将通过简单地更新其 npm 依赖来升级。

¥This is not a full rewrite, and the breaking changes are relatively easy to handle. The simplest sites will eventually upgrade by simply updating their npm dependencies.

主要的重大变化是从 MDX v1 升级到 MDX v3。有关详细信息,请阅读 MDX v2MDX v3 发行说明。MDX 现在将更严格地编译你的 Markdown 内容,并存在细微的差异。

¥The main breaking change is the upgrade from MDX v1 to MDX v3. Read the MDX v2 and MDX v3 release notes for details. MDX will now compile your Markdown content more strictly and with subtle differences.

升级前

升级之前,我们推荐 为 Docusaurus v3 准备你的网站。在 Docusaurus v2 下,你已经可以增量处理一些更改。这样做将有助于减少最终升级到 Docusaurus v3 所需的工作。

¥Before upgrading, we recommend preparing your site for Docusaurus v3. There are changes that you can already handle incrementally, under Docusaurus v2. Doing so will help reduce the work needed to finally upgrade to Docusaurus v3.

对于复杂的网站,我们还建议设置 视觉回归测试,这是确保你的网站在视觉上保持相同的好方法。Docusaurus v3 主要升级依赖,预计不会产生任何视觉变化。

¥For complex sites, we also recommend to set up visual regression tests, a good way to ensure your site stays visually identical. Docusaurus v3 mainly upgrades dependencies, and is not expected to produce any visual changes.

注意

检查 Docusaurus v3.0.0 的发行说明,并浏览拉取请求以获取其他有用的信息以及此处提到的每个更改背后的动机。

¥Check the release notes for Docusaurus v3.0.0, and browse the pull-requests for additional useful information and the motivation behind each change mentioned here.

升级依赖

¥Upgrading Dependencies

升级到 Docusaurus v3 需要升级核心 Docusaurus 依赖 (@docusaurus/name),还需要升级其他相关软件包。

¥Upgrading to Docusaurus v3 requires upgrading core Docusaurus dependencies (@docusaurus/name), but also other related packages.

Docusaurus v3 现在使用以下依赖:

¥Docusaurus v3 now uses the following dependencies:

  • Node.js v18.0+

  • React v18.0+

  • MDX v3.0+

  • TypeScript v5.1+

  • Prisma 反应渲染器 v2.0+

    ¥prism-react-renderer v2.0+

  • 反应实时 v4.0+

    ¥react-live v4.0+

  • remark-emoji v4.0+

  • mermaid v10.4+

升级社区插件

如果你的网站使用第三方社区插件和主题,你可能需要升级它们。

¥If your site uses third-party community plugins and themes, you might need to upgrade them.

在尝试升级之前,请确保这些插件与 Docusaurus v3 兼容。

¥Make sure those plugins are compatible with Docusaurus v3 before attempting an upgrade.

一个典型的 package.json 依赖升级示例:

¥A typical package.json dependency upgrade example:

package.json
 {
"dependencies": {
// upgrade to Docusaurus v3
- "@docusaurus/core": "2.4.3",
- "@docusaurus/preset-classic": "2.4.3",
+ "@docusaurus/core": "3.0.0",
+ "@docusaurus/preset-classic": "3.0.0",
// upgrade to MDX v3
- "@mdx-js/react": "^1.6.22",
+ "@mdx-js/react": "^3.0.0",
// upgrade to prism-react-renderer v2.0+
- "prism-react-renderer": "^1.3.5",
+ "prism-react-renderer": "^2.1.0",
// upgrade to React v18.0+
- "react": "^17.0.2",
- "react-dom": "^17.0.2"
+ "react": "^18.2.0",
+ "react-dom": "^18.2.0"
},
"devDependencies": {
// upgrade Docusaurus dev dependencies to v3
- "@docusaurus/module-type-aliases": "2.4.3",
- "@docusaurus/types": "2.4.3"
+ "@docusaurus/module-type-aliases": "3.0.0",
+ "@docusaurus/types": "3.0.0"
}
"engines": {
// require Node.js 18.0+
- "node": ">=16.14"
+ "node": ">=18.0"
}
}

对于 TypeScript 用户:

¥For TypeScript users:

package.json
 {
"devDependencies": {
// swap the external TypeScript config package for the new official one
- "@tsconfig/docusaurus": "^1.0.7",
+ "@docusaurus/tsconfig": "3.0.0",
// upgrade React types to v18.0+
- "@types/react": "^17.0.69",
+ "@types/react": "^18.2.29",
// upgrade TypeScript to v5.1+
- "typescript": "~4.7.4"
+ "typescript": "~5.2.2"
}
}

升级 MDX

¥Upgrading MDX

MDX 是 Docusaurus 的主要依赖,负责将 .md.mdx 文件编译为 React 组件。

¥MDX is a major dependency of Docusaurus responsible for compiling your .md and .mdx files to React components.

从 MDX v1 到 MDX v3 的过渡是采用 Docusaurus v3 的主要挑战。大多数重大更改来自 MDX v2,而 MDX v3 是一个相对较小的版本。

¥The transition from MDX v1 to MDX v3 is the main challenge to the adoption of Docusaurus v3. Most breaking changes come from MDX v2, and MDX v3 is a relatively small release.

一些在 Docusaurus v2 下成功编译的文档现在可能无法在 Docusaurus v3 下编译。

¥Some documents that compiled successfully under Docusaurus v2 might now fail to compile under Docusaurus v3.

提前发现有问题的内容

在你的站点上运行 npx docusaurus-mdx-checker 以获取现在在 Docusaurus v3 下无法编译的文件列表。

¥Run npx docusaurus-mdx-checker on your site to get a list of files that will now fail to compile under Docusaurus v3.

此命令也是估计使内容兼容所需完成的工作量的好方法。请记住,大部分工作可以在 为 Docusaurus v3 准备内容 升级之前执行。

¥This command is also a good way to estimate the amount of work to be done to make your content compatible. Remember most of this work can be executed ahead of the upgrade by preparing your content for Docusaurus v3.

其他文档也可能以不同的方式渲染。

¥Other documents might also render differently.

使用视觉回归测试

对于手动审查所有页面很复杂的大型网站,我们建议你设置 视觉回归测试

¥For large sites where a manual review of all pages is complicated, we recommend you to setup visual regression tests.

升级 MDX 附带 MDX v2MDX v3 发布博客文章中记录的所有重大更改。大多数重大更改来自 MDX v2,而 MDX v3 是一个相对较小的版本。MDX v2 迁移指南 有一个关于如何 更新 MDX 文件 的部分,这与我们特别相关。另请务必阅读 MDX 故障排除 页面,它可以帮助你解释常见的 MDX 错误消息。

¥Upgrading MDX comes with all the breaking changes documented on the MDX v2 and MDX v3 release blog posts. Most breaking changes come from MDX v2, and MDX v3 is a relatively small release. The MDX v2 migration guide has a section on how to update MDX files that will be particularly relevant to us. Also make sure to read the Troubleshooting MDX page that can help you interpret common MDX error messages.

请务必阅读我们更新的 MDX 和 React 文档页面。

¥Make sure to also read our updated MDX and React documentation page.

使用 MDX 在线运行

¥Using the MDX playground

MDX 在线运行是你最好的新朋友。它允许了解你的内容如何编译为 React 组件,并单独解决编译或渲染问题。

¥The MDX playground is your new best friend. It permits to understand how your content is compiled to React components, and troubleshoot compilation or rendering issues in isolation.

Configuring the MDX playground options for Docusaurus

要获得类似于 Docusaurus v2 使用的编译行为,请在 MDX 在线运行 上打开以下选项:

¥To obtain a compilation behavior similar to what Docusaurus v2 uses, please turn on these options on the MDX playground:

  • 使用 MDX

    ¥Use MDX

  • 使用 remark-gfm

    ¥Use remark-gfm

  • 使用 remark-directive

    ¥Use remark-directive

Screenshot of the MDX playground's options panel, with only the "Use MDX", "Use remark-gfm", and "Use remark-directive" options checked

并排使用两个 MDX 在线运行,你很快就会注意到某些内容的编译方式不同或无法在 v2 中编译。

¥Using the two MDX playgrounds side-by-side, you will soon notice that some content is compiled differently or fails to compile in v2.

让你的内容面向未来

目标是重构有问题的内容,使其在两个版本的 MDX 中都能正常工作。这样,当你升级到 Docusaurus v3 时,此内容就已经可以开箱即用了。

¥The goal will be to refactor your problematic content so that it works fine with both versions of MDX. This way, when you upgrade to Docusaurus v3, this content will already work out-of-the-box.

使用 MDX 检查器 CLI

¥Using the MDX checker CLI

我们提供了 docusaurus-mdx-checker CLI,可以轻松发现有问题的内容。在你的站点上运行此命令以获取在 MDX v3 下无法编译的文件列表。

¥We provide a docusaurus-mdx-checker CLI that permits to easily spot problematic content. Run this command on your site to obtain a list of files that will fail to compile under MDX v3.

npx docusaurus-mdx-checker

对于每个编译问题,CLI 将记录文件路径和行号以供查看。

¥For each compilation issue, the CLI will log the file path and a line number to look at.

Screenshot of the terminal showing an example MDX checker CLI output, with a few error messages

提示

使用此 CLI 来估计使你的内容与 MDX v3 兼容需要多少工作。

¥Use this CLI to estimate of how much work will be required to make your content compatible with MDX v3.

警告

此 CLI 已尽最大努力,并且只会报告编译错误。

¥This CLI is a best effort, and will only report compilation errors.

它不会报告不会产生错误但会影响内容显示方式的细微编译更改。为了解决这些问题,我们建议使用 视觉回归测试

¥It will not report subtle compilation changes that do not produce errors but can affect how your content is displayed. To catch these problems, we recommend using visual regression tests.

常见 MDX 问题

¥Common MDX problems

Docusaurus 无法详尽记录 MDX 带来的所有更改。这是 MDX v2MDX v3 迁移指南的职责。

¥Docusaurus cannot document exhaustively all the changes coming with MDX. That's the responsibility of the MDX v2 and MDX v3 migration guides.

然而,通过升级一些 Docusaurus 站点,我们注意到大多数问题都归结为我们为你记录的少数案例。

¥However, by upgrading a few Docusaurus sites, we noticed that most of the issues come down to only a few cases that we have documented for you.

{ 的错误使用

¥Bad usage of {

{ 字符用于打开 JavaScript 表达式。如果你在 {expression} 中放入的内容不是有效的表达式,MDX 现在将会失败。

¥The { character is used for opening JavaScript expressions. MDX will now fail if what you put inside {expression} is not a valid expression.

example.md
The object shape looks like {username: string, age: number}
错误信息

无法用 acorn 解析表达式:表达后出现意外内容

¥Could not parse expression with acorn: Unexpected content after expression

如何升级

修复此错误的可用选项:

¥Available options to fix this error:

  • 使用内联代码:{username: string, age: number}

    ¥Use inline code: {username: string, age: number}

  • 使用 HTML 代码:{

    ¥Use the HTML code: {

  • 转义它:\{

    ¥Escape it: \{

< 的错误使用

¥Bad usage of <

< 字符用于打开 JSX 标签。如果 MDX 认为你的 JSX 无效,它现在将会失败。

¥The < character is used for opening JSX tags. MDX will now fail if it thinks your JSX is invalid.

example.md
Use Android version <5

You can use a generic type like Array<T>

Follow the template "Road to <YOUR_MINOR_VERSION>"
错误信息

名称前有意外字符 5 (U+0035),应为可启动名称的字符,例如字母、$_

¥Unexpected character 5 (U+0035) before name, expected a character that can start a name, such as a letter, $, or _

预计在 paragraph 结束标记不匹配 mdast-util-mdx-jsx 结束之前有 <T> (1:6-1:9) 的结束标记

¥Expected a closing tag for <T> (1:6-1:9) before the end of paragraph end-tag-mismatch mdast-util-mdx-jsx

预计 paragraph 结束前 <YOUR_MINOR_VERSION> (134:19-134:39) 会有结束标签

¥Expected a closing tag for <YOUR_MINOR_VERSION> (134:19-134:39) before the end of paragraph

如何升级

修复此错误的可用选项:

¥Available options to fix this error:

  • 使用内联代码:Array<T>

    ¥Use inline code: Array<T>

  • 使用 HTML 代码:&lt;&#60;

    ¥Use the HTML code: &lt; or &#60;

  • 转义它:\<

    ¥Escape it: \<

¥Bad usage of GFM Autolink

Docusaurus 支持 GitHub 风格的 Markdown (GFM),但 MDX 不再支持使用 <link> 语法的 autolink

¥Docusaurus supports GitHub Flavored Markdown (GFM), but autolink using the <link> syntax is not supported anymore by MDX.

example.md
<sebastien@thisweekinreact.com>

http://localhost:3000
错误信息

名称中存在意外字符 @ (U+0040),应为字母、数字、$_ 等名称字符;属性前有空格;或标记的末尾(注意:要在 MDX 中创建链接,请使用 [text](url)

¥Unexpected character @ (U+0040) in name, expected a name character such as letters, digits, $, or _; whitespace before attributes; or the end of the tag (note: to create a link in MDX, use [text](url))

本地名称前有意外字符 / (U+002F),应为可以启动名称的字符,例如字母、$_(注意:要在 MDX 中创建链接,请使用 [text](url))

¥Unexpected character / (U+002F) before local name, expected a character that can start a name, such as a letter, $, or _ (note: to create a link in MDX, use [text](url))

如何升级

使用常规 Markdown 链接,或删除 <>。MDX 和 GFM 已经能够自动链接字面量。

¥Use regular Markdown links, or remove the < and >. MDX and GFM are able to autolink literals already.

example.md
sebastien@thisweekinreact.com
[sebastien@thisweekinreact.com](mailto:sebastien@thisweekinreact.com)

http://localhost:3000
[http://localhost:3000](http://localhost:3000)

小写 MDXComponent 映射

¥Lower-case MDXComponent mapping

对于提供 自定义 MDXComponent 映射 的用户,组件现在为 "sandboxed":

¥For users providing a custom MDXComponentmapping, components are now "sandboxed":

  • h1MDXComponent 映射仅用于 # hi,但不用于 <h1>hi</h1>

    ¥a MDXComponent mapping for h1 only gets used for # hi but not for <h1>hi</h1>

  • 小写的自定义元素名称将不再被其各自的 MDXComponent 组件替换

    ¥a lower-cased custom element name will not be substituted by its respective MDXComponent component anymore

视觉差异

你的 MDXComponent 组件映射 可能不会像以前一样应用,并且你的自定义组件可能不再使用。

¥Your MDXComponent component mapping might not be applied as before, and your custom components might no longer be used.

如何升级

对于原生 Markdown 元素,你可以继续使用小写:ph1imga...

¥For native Markdown elements, you can keep using lower-case: p, h1, img, a...

对于任何其他元素,请使用大写名称。

¥For any other element, use upper-case names.

src/theme/MDXComponents.js
 import MDXComponents from '@theme-original/MDXComponents';

export default {
...MDXComponents,
p: (props) => <p {...props} className="my-paragraph"/>
- myElement: (props) => <div {...props} className="my-class" />,
+ MyElement: (props) => <div {...props} className="my-class" />,
};

意外的额外段落

¥Unintended extra paragraphs

在 MDX v3 中,现在可以更轻松地交错 JSX 和 Markdown,而无需额外的换行符。在多行上写入内容也可以产生新的预期 <p> 标签。

¥In MDX v3, it is now possible to interleave JSX and Markdown more easily without requiring extra line breaks. Writing content on multiple lines can also produce new expected <p> tags.

视觉差异

了解 MDX v1 和 v3 如何以不同的方式渲染此内容。

¥See how this content is rendered differently by MDX v1 and v3.

example.md
<div>Some **Markdown** content</div>
<div>
Some **Markdown** content
</div>
MDX v1 output
<div>Some **Markdown** content</div>
<div>Some **Markdown** content</div>
MDX v3 output
<div>Some <strong>Markdown</strong> content</div>
<div><p>Some <strong>Markdown</strong> content</p></div>
如何升级

如果你不需要额外的 <p> 标记,请根据具体情况重构内容以使用单行 JSX 标记。

¥If you don't want an extra <p> tag, refactor content on a case by case basis to use a single-line JSX tag.

 <figure>
<img src="/img/myImage.png" alt="My alt" />
- <figcaption>
- My image caption
- </figcaption>
+ <figcaption>My image caption</figcaption>
</figure>

如果你不打算在那里使用 Markdown 语法,你还可以使用 {} 封装此类内容以避免额外的 <p> 标签。

¥You can also wrap such content with { and } to avoid extra <p> tags if you don't intend to use Markdown syntax there yet.

-<figure>
+{<figure>
<img src="/img/myImage.png" alt="My alt" />
<figcaption>
My image caption
</figcaption>
-</figure>
+</figure>}

指令的意外使用

¥Unintended usage of directives

Docusaurus v3 现在使用 Markdown 指令(通过 remark-directive 实现)作为通用方式来提供对警告和其他即将推出的 Docusaurus 功能的支持。

¥Docusaurus v3 now uses Markdown Directives (implemented with remark-directive) as a generic way to provide support for admonitions, and other upcoming Docusaurus features.

example.md
This is a :textDirective

::leafDirective



:::containerDirective



Container directive content



:::


视觉变化

解析指令的目的是由其他 Remark 插件处理。未处理的指令将被忽略,并且不会以其原始形式渲染。

¥Directives are parsed with the purpose of being handled by other Remark plugins. Unhandled directives will be ignored, and won't be rendered back in their original form.

example.md
The AWS re:Invent conf is great

由于 :Invent 被解析为文本指令,因此现在将渲染为:

¥Due to :Invent being parsed as a text directive, this will now be rendered as:

The AWS re
conf is great
如何升级
  • 使用 HTML 代码:&#58;

    ¥Use the HTML code: &#58;

  • : 之后添加一个空格(如果有意义的话):: text

    ¥Add a space after : (if it makes sense): : text

  • 转义它:\:

    ¥Escape it: \:

不支持的缩进代码块

¥Unsupported indented code blocks

MDX 不再将缩进文本转换为代码块。

¥MDX does not transform indented text as code blocks anymore.

example.md
    console.log("hello");
视觉变化

升级通常不会产生新的 MDX 编译错误,但可能会导致内容以意外方式渲染,因为不再有代码块。

¥The upgrade does not generally produce new MDX compilation errors, but can lead to content being rendered in an unexpected way because there isn't a code block anymore.

如何升级

使用常规代码块语法而不是缩进:

¥Use the regular code block syntax instead of indentation:

example.md
```js
console.log('hello');
```

其他 Markdown 不兼容性

¥Other Markdown incompatibilities

强调以空格或标点符号开头或结尾

¥Emphasis starting or ending with a space or a punctuation

新的 MDX 解析器现在严格遵守 CommonMark 规范。自 v0.14 起,CommonMark 规范引入了强调空格和标点符号的规则,特别是与不使用空格来分割单词的语言不兼容。

¥New MDX parser now strictly complies with the CommonMark spec. CommonMark spec has introduced rules for emphasis around spaces and punctuation, which are incompatible especially with languages that do not use a space to split words, since v0.14.

日语和中文受此影响最大,但还有一些其他语言可能会受到影响(例如泰语和高棉语),例如当你尝试强调内联代码或链接时。使用空格来分割单词的语言受到的影响要小得多。

¥Japanese and Chinese are most affected by this, but there are some other languages that can be affected (e.g. Thai and Khmer), for example when you try to emphasize an inline code or a link. Languages that use a space to split words are much less affected.

以下示例中的 **** 除外)按照 Docusaurus 2 中的预期进行解析,但现在不在 Docusaurus 3 中。

¥** (other than `**`) in the following example were parsed as intended in Docusaurus 2, but are not now in Docusaurus 3.

example.md
**Do not end a range of emphasis with a space. **Or `**` will not work as intended.

<!-- Japanese -->
**「。」の後に文を続けると`**`が意図した動作をしません。**また、**[リンク](https://docusaurus.nodejs.cn/)****`コード`**のすぐ外側に`**`、そのさらに外側に句読点以外がある場合も同様です。
See the detailed conditions and how to upgrade

如果 *** 符合以下任一条件,则它将不再作为强调标记的开头:

¥If * or ** matches either of the following conditions, it will not work as the beginning of an emphasis mark anymore:

  • 下一个字符是空格(例如 word* word

    ¥The next character is a space (e.g. word* word)

  • 前一个字符是标点字符,下一个字符是字母(不是空格或标点字符)(例如 文**(文)

    ¥The previous character is a punctuation character and the next character is a letter (not a space or punctuation character) (e.g. 文**(文))

相反,如果 *** 符合以下任一条件,则不再作为强调标记的结尾:

¥On the contrary, if * or ** matches either of the following conditions, it will not work as the end of an emphasis mark anymore:

  • 前一个字符是空格(例如 word *word

    ¥The previous character is a space (e.g. word *word)

  • 下一个字符是标点符号,前一个字符是字母(例如 文。**文

    ¥The next character is a punctuation character and the previous character is a letter (e.g. 文。**文)

“标点字符”包括非 ASCII 字符、括号、引号和一些符号,包括 %@。更严格地说,这里将 2 个字母的 Unicode 类别以 P 开头的字符视为标点符号。

¥“A punctuation character” includes non-ASCII ones, brackets, quotation marks and some symbols including % and @. More strictly speaking, a character whose 2-letters Unicode category starts with P is treated as a punctuation character here.

如何升级

如果有问题的强调标记位于空格旁边,则将该空格移出强调范围:

¥If the offending emphasis mark is next to a space, move the space out of the range of emphasis:

english.md
**Do not end a range of emphasis with a space.** Or `**` will not work.

如果有问题的强调标记被标点符号和字母包围,你可以通过以下方式修复它而不修改内容:

¥If the offending emphasis mark is surrounded by both a punctuation character and a letter, you can fix it without modifying the content by:

  1. 如果文档是普通 Markdown,请将其转换为 MDX。

    ¥Convert the document to MDX if it is a vanilla Markdown.

  2. 将有问题的强调标记替换为原始 HTML 标记(<em><strong>):

    ¥replace the offending emphasis mark with a raw HTML tag (<em> or <strong>) instead:

japanese.mdx
<strong>「。」の後に文を続けると`**`が意図した動作をしません。</strong>また、<strong>[リンク](https://docusaurus.nodejs.cn/)</strong>や<strong>`コード`</strong>のすぐ外側に`**`、そのさらに外側に句読点以外がある場合も同様です。

虽然这不是理想的解决方案,但你也可以执行以下任一操作,而无需将文档转换为 MDX:

¥While not an ideal solution, you can also either of the following without converting the document to MDX:

  • 将最外面的标点符号移出强调标记。

    ¥Move the most outside punctuation character out of the emphasis mark.

    japanese.md
    **「。」の後に文を続けると`**`が意図した動作をしません**。また、[**リンク**](https://docusaurus.nodejs.cn/)や・・・
  • 在有问题的 *** 外面留一个空格。此解决方案不会强制你将文档转换为 MDX。

    ¥Put a space just outside of the offending * or **. This solution does not force you to convert the document to MDX.

    japanese.md
    **「。」の後に文を続けると`**`が意図した動作をしません。** また、**[リンク](https://docusaurus.nodejs.cn/)****`コード`** のすぐ外側に`**`、そのさらに外側に句読点以外がある場合も同様です。

MDX 插件

¥MDX plugins

MDX 生态系统中的所有官方软件包(Unified、Remark、Rehype...)现在都是 仅 ES 模块,不再支持 CommonJS

¥All the official packages (Unified, Remark, Rehype...) in the MDX ecosystem are now ES Modules only and do not support CommonJS anymore.

实际上,这意味着你不能再执行 require("remark-plugin")

¥In practice this means that you can't do require("remark-plugin") anymore.

如何升级

Docusaurus v3 现在支持 ES 模块 配置文件。我们建议你将配置文件迁移到 ES 模块,这样你就可以轻松导入 Remark 插件:

¥Docusaurus v3 now supports ES Modules configuration files. We recommend that you migrate your config file to ES module, that enables you to import the Remark plugins easily:

docusaurus.config.js
import remarkPlugin from 'remark-plugin';

export default {
title: 'Docusaurus',
/* site config using remark plugins here */
};

如果你想继续使用 CommonJS 模块,可以使用动态导入作为解决方法,使你能够在 CommonJS 模块内导入 ES 模块。幸运的是,Docusaurus 配置支持使用异步函数 让你这样做。

¥If you want to keep using CommonJS modules, you can use dynamic imports as a workaround that enables you to import ES modules inside a CommonJS module. Fortunately, the Docusaurus config supports the usage of an async function to let you do so.

docusaurus.config.js
module.exports = async function () {
const myPlugin = (await import('remark-plugin')).default;
return {
// site config...
};
};
对于插件作者

如果你创建了自定义 Remark 或 Rehype 插件,则由于新 AST 的结构方式,你可能需要重构这些插件,或者最终完全重写它们。我们创建了 专门的支持讨论 来帮助插件作者升级他们的代码。

¥If you created custom Remark or Rehype plugins, you may need to refactor those, or eventually rewrite them completely, due to how the new AST is structured. We have created a dedicated support discussion to help plugin authors upgrade their code.

格式化器

¥Formatters

Prettier 是最常见的格式化程序,仅支持旧版 MDX v1,自 Docusaurus v3.0.0 起尚不支持 v3。你可以在代码的不兼容部分之前添加 {/* prettier-ignore */},以使其与 Prettier 一起使用。

¥Prettier, the most common formatter, supports only the legacy MDX v1, not v3 yet as of Docusaurus v3.0.0. You can add {/* prettier-ignore */} before the incompatible parts of your code to make it work with Prettier.

{/* prettier-ignore */}
<SomeComponent>Some long text in the component</SomeComponent>

如果你厌倦了太多的 {/* prettier-ignore */} 插入,你可以考虑通过将以下内容添加到 .prettierignore 文件来禁用 Prettier 的 MDX 格式化,直到它开始支持 MDX v3:

¥If you get tired of too many {/* prettier-ignore */} insertions, you can consider disabling MDX formatting by Prettier by adding the following to your .prettierignore file, until it starts supporting MDX v3:

.prettierignore
*.mdx

其他重大变化

¥Other Breaking Changes

除了 MDX v3 升级之外,这里还列出了 Docusaurus v3 带来的重大更改。

¥Apart the MDX v3 upgrade, here is an exhaustive list of breaking changes coming with Docusaurus v3.

Node.js v18.0

Node.js 16 已达到使用寿命 和 Docusaurus v3 现在需要 Node.js >= 18.0。

¥Node.js 16 reached End-of-Life, and Docusaurus v3 now requires Node.js >= 18.0.

如何升级

在你的计算机上安装 Node.js 18.0+。

¥Install Node.js 18.0+ on your computer.

最后,配置你的持续集成、CDN 或主机以使用这个新的 Node.js 版本。

¥Eventually, configure your continuous integration, CDN or host to use this new Node.js version.

你还可以更新你的站点 package.json 以防止使用不受支持的旧版本:

¥You can also update your site package.json to prevent usage of an older unsupported version:

package.json
 {
"engines": {
- "node": ">=16.14"
+ "node": ">=18.0"
}
}

在升级到 Docusaurus v3 之前,请将 Docusaurus v2 站点升级到 Node.js 18。

¥Upgrade your Docusaurus v2 site to Node.js 18 before upgrading to Docusaurus v3.

React v18.0+

Docusaurus v3 现在需要 React >= 18.0。

¥Docusaurus v3 now requires React >= 18.0.

React 18 附带了自己的重大更改,这些更改应该相对容易处理,具体取决于你为站点创建的自定义 React 代码的数量。官方主题和插件与 React 18 兼容。

¥React 18 comes with its own breaking changes that should be relatively easy to handle, depending on the amount of custom React code you created for your site. The official themes and plugins are compatible with React 18.

如何升级

阅读官方的 反应 v18.0如何升级到 React 18,并查看你自己的 React 代码以找出哪些组件可能会受到此次升级的影响。

¥Read the official React v18.0 and How to Upgrade to React 18, and look at your own React code to figure out which components might be affected this upgrade.

我们建议特别寻找:

¥We recommend to particularly look for:

  • 有状态组件的自动批处理

    ¥Automatic batching for stateful components

  • 新的 React 水合错误报告给控制台

    ¥New React hydration errors reported to the console

对 React 18 功能的实验性支持

React 18 带来了新功能:

¥React 18 comes with new features:

  • <Suspense>

  • React.lazy()

  • startTransition

他们的 Docusaurus 支持被认为是实验性的。我们将来可能需要调整集成,从而导致不同的运行时行为。

¥Their Docusaurus support is considered as experimental. We might have to adjust the integration in the future, leading to a different runtime behavior.

Prism-React-Renderer v2.0+

Docusaurus v3 将 prism-react-renderer 升级到 v2.0+。该库用于代码块语法高亮。

¥Docusaurus v3 upgrades prism-react-renderer to v2.0+. This library is used for code block syntax highlighting.

如何升级

这是一个新的主要库版本,包含重大更改,我们不能保证严格的向后兼容性。prism-react-renderer v2 发行说明 并不是非常详尽,但 Docusaurus 用户需要注意 3 个主要变化。

¥This is a new major library version containing breaking changes, and we can't guarantee a strict retro-compatibility. The prism-react-renderer v2 release notes are not super exhaustive, but there are 3 major changes to be aware of for Docusaurus users.

应升级依赖:

¥The dependency should be upgraded:

package.json
 {
"dependencies": {
- "prism-react-renderer": "^1.3.5",
+ "prism-react-renderer": "^2.1.0",
}

用于在 Docusaurus 配置文件中导入主题的 API 已更新:

¥The API to import themes in your Docusaurus config file has been updated:

docusaurus.config.js
- const lightTheme = require('prism-react-renderer/themes/github');
- const darkTheme = require('prism-react-renderer/themes/dracula');
+ const {themes} = require('prism-react-renderer');
+ const lightTheme = themes.github;
+ const darkTheme = themes.dracula;

此前,react-prism-render v1 默认包含更多语言。从 v2.0+ 开始,默认情况下包含的语言较少。你可能需要向 Docusaurus 配置添加额外的语言:

¥Previously, react-prism-render v1 included more languages by default. From v2.0+, less languages are included by default. You may need to add extra languages to your Docusaurus config:

docusaurus.config.js
const siteConfig = {
themeConfig: {
prism: {
additionalLanguages: ['bash', 'diff', 'json'],
},
},
};

React-Live v4.0+

对于 @docusaurus/theme-live-codeblock 软件包的用户,Docusaurus v3 将 react-live 升级到 v4.0+。

¥For users of the @docusaurus/theme-live-codeblock package, Docusaurus v3 upgrades react-live to v4.0+.

如何升级

理论上,你无需执行任何操作,现有的交互式代码块应该像以前一样继续工作。

¥In theory, you have nothing to do, and your existing interactive code blocks should keep working as before.

然而,这是一个新的主要库版本,包含重大更改,我们不能保证严格的向后兼容性。如果出现问题,请阅读 v3v4 变更日志。

¥However, this is a new major library version containing breaking changes, and we can't guarantee a strict retro-compatibility. Read the v3 and v4 changelogs in case of problems.

remark-emoji v4.0+

Docusaurus v3 将 remark-emoji 升级到 v4.0+。该库是为了支持 Markdown 中的 :emoji: 快捷键。

¥Docusaurus v3 upgrades remark-emoji to v4.0+. This library is to support :emoji: shortcuts in Markdown.

如何升级

大多数 Docusaurus 用户无事可做。表情符号短代码的用户应阅读 changelog 并仔细检查其表情符号是否按预期渲染。

¥Most Docusaurus users have nothing to do. Users of emoji shortcodes should read the changelog and double-check their emojis keep rendering as expected.

重大变更更新 node-emoji 从 v1 到 v2。此更改引入了对许多新表情符号的支持,并删除了 GitHub 上不再有效的旧表情符号短代码。

¥Breaking Change Update node-emoji from v1 to v2. This change introduces support for many new emojis and removes old emoji short codes which are no longer valid on GitHub.

Mermaid v10.4+

对于 @docusaurus/theme-mermaid 软件包的用户,Docusaurus v3 将 mermaid 升级到 v10.4+。

¥For users of the @docusaurus/theme-mermaid package, Docusaurus v3 upgrades mermaid to v10.4+.

如何升级

理论上,你无需执行任何操作,现有图表应该像以前一样继续工作。

¥In theory, you have nothing to do, and your existing diagrams should keep working as before.

然而,这是一个新的主要库版本,包含重大更改,我们不能保证严格的向后兼容性。如果出现问题,请阅读 v10 变更日志。

¥However, this is a new major library version containing breaking changes, and we can't guarantee a strict retro-compatibility. Read the v10 changelog in case of problem.

TypeScript v5.1+

Docusaurus v3 现在需要 TypeScript >= 5.1。

¥Docusaurus v3 now requires TypeScript >= 5.1.

如何升级

升级你的依赖以使用 TypeScript 5+

¥Upgrade your dependencies to use TypeScript 5+

package.json
 {
"devDependencies": {
- "typescript": "~4.7.4"
+ "typescript": "~5.2.2"
}
}

TypeScript 基本配置

¥TypeScript base config

官方 Docusaurus TypeScript 配置已从外部包 @tsconfig/docusaurus 重新内部化到我们新的 monorepo 包 @docusaurus/tsconfig

¥The official Docusaurus TypeScript config has been re-internalized from the external package @tsconfig/docusaurus to our new monorepo package @docusaurus/tsconfig.

这个新包与所有其他 Docusaurus 核心包一起进行版本控制,并将用于确保 TypeScript 的向后兼容性和主要版本升级的重大更改。

¥This new package is versioned alongside all the other Docusaurus core packages, and will be used to ensure TypeScript retro-compatibility and breaking changes on major version upgrades.

如何升级

将外部 TypeScript 配置包替换为新的官方配置包

¥Swap the external TypeScript config package for the new official one

package.json
 {
"devDependencies": {
- "@tsconfig/docusaurus": "^1.0.7",
+ "@docusaurus/tsconfig": "3.0.0",
}
}

tsconfig.json 文件中使用它:

¥Use it in your tsconfig.json file:

tsconfig.json
 {
- "extends": "@tsconfig/docusaurus/tsconfig.json",
+ "extends": "@docusaurus/tsconfig",
"compilerOptions": {
"baseUrl": "."
}
}

新的配置加载器

¥New Config Loader

Docusaurus v3 将其内部配置加载库从 import-fresh 更改为 jiti。它负责加载 docusaurus.config.jssidebars.js 等文件以及 Docusaurus 插件。

¥Docusaurus v3 changes its internal config loading library from import-fresh to jiti. It is responsible for loading files such as docusaurus.config.js or sidebars.js, and Docusaurus plugins.

如何升级

理论上,你无需执行任何操作,现有的配置文件应该像以前一样继续工作。

¥In theory, you have nothing to do, and your existing config files should keep working as before.

然而,这是一个主要的依赖交换,并且可能会发生微妙的行为变化。

¥However, this is a major dependency swap and subtle behavior changes could occur.

告诫警告

¥Admonition Warning

由于历史原因,我们支持未记录的警告 :::warning,它渲染为红色。

¥For historical reasons, we support an undocumented admonition :::warning that renders with a red color.

警告

这是 Docusaurus v2 :::warning 警告。

¥This is a Docusaurus v2 :::warning admonition.

然而,颜色和图标始终是错误的。Docusaurus v3 正式重新引入 :::warning 警告,对其进行记录,并修复颜色和图标。

¥However, the color and icon have always been wrong. Docusaurus v3 re-introduces :::warning admonition officially, documents it, and fix the color and icon.

警告

这是 Docusaurus v3 :::warning 警告。

¥This is a Docusaurus v3 :::warning admonition.

如何升级

如果你之前使用过未记录的 :::warning 警告,请确保每次使用时都验证黄色现在是否是合适的颜色。如果你想保留红色,请使用 :::danger

¥If you previously used the undocumented :::warning admonition, make sure to verify for each usage if yellow is now an appropriate color. If you want to keep the red color, use :::danger instead.

Docusaurus v3 也有 已弃用 :::caution 警告。请将 :::caution(黄色)重构为 :::warning(黄色)或 :::danger(红色)。

¥Docusaurus v3 also deprecated the :::caution admonition. Please refactor :::caution (yellow) to either :::warning (yellow) or :::danger (red).

如果你想保留标题“警告”,你可能需要将其重构为 :::warning[caution](黄色)。

¥If you want to keep the title “caution”, you might want to refactor it to :::warning[caution] (yellow).

版本化侧边栏

¥Versioned Sidebars

这一重大更改只会影响在 v2.0.0-beta.10(2021 年 12 月)之前版本化文档的 Docusaurus v2 早期采用者。

¥This breaking change will only affect Docusaurus v2 early adopters who versioned their docs before v2.0.0-beta.10 (December 2021).

创建版本 v1.0.0 时,侧边栏文件包含前缀 version-v1.0.0/,即 Docusaurus v3 不再支持

¥When creating version v1.0.0, the sidebar file contained a prefix version-v1.0.0/ that Docusaurus v3 does not support anymore.

versioned_sidebars/version-v1.0.0-sidebars.json
{
"version-v1.0.0/docs": [
"version-v1.0.0/introduction",
"version-v1.0.0/prerequisites"
]
}
如何升级

从版本化侧边栏中删除无用的版本化前缀。

¥Remove the useless versioned prefix from your versioned sidebars.

versioned_sidebars/version-v1.0.0-sidebars.json
{
"docs": ["introduction", "prerequisites"]
}

博客提要限制

¥Blog Feed Limit

@docusaurus/plugin-content-blog 现在默认将 RSS 提要限制为最后 20 个条目。对于大型 Docusaurus 博客,这是一个更明智的默认值,以避免 RSS 文件变得越来越大。

¥The @docusaurus/plugin-content-blog now limits the RSS feed to the last 20 entries by default. For large Docusaurus blogs, this is a more sensible default value to avoid an increasingly large RSS file.

如何升级

如果你不喜欢这个新的默认行为,你可以使用新的 limit: false feed 选项恢复到以前的 "无限饲料" 行为:

¥In case you don't like this new default behavior, you can revert to the former "unlimited feed" behavior with the new limit: false feed option:

docusaurus.config.js
const blogOptions = {
feedOptions: {
limit: false,
},
};

文档主题重构

¥Docs Theme Refactoring

对于使用与文档相关的主题组件(如 @theme/DocPage)的用户,这些组件已进行了重大重构,以使其更易于自定义。

¥For users that swizzled docs-related theme components (like @theme/DocPage), these components have been significantly refactor to make it easier to customize.

从技术上讲,这并不是一个重大更改,因为这些组件被标记为不安全,但许多 Docusaurus 站点弹出了与文档相关的组件,并且有兴趣知道它们的自定义可能会破坏 Docusaurus。

¥Technically, this is not a breaking change because these components are flagged as unsafe to swizzle, however many Docusaurus sites ejected docs-related components, and will be interested to know their customizations might break Docusaurus.

如何升级

删除所有混合组件,重新混合它们,然后在新更新的组件之上重新应用你的自定义设置。

¥Delete all your swizzled components, re-swizzle them, and re-apply your customizations on top of the newly updated components.

或者,你可以查看 拉取请求注释 以了解新的主题组件树结构,并最终尝试手动修补混合后的组件。

¥Alternatively, you can look at the pull-request notes to understand the new theme component tree structure, and eventually try to patch your swizzled components manually.

可选更改

¥Optional Changes

有些更改不是强制性的,但为了清楚地利用 Docusaurus v3 仍然很有用。

¥Some changes are not mandatory, but remain useful to be aware of to plainly leverage Docusaurus v3.

自动 JSX 运行时

¥Automatic JSX runtime

Docusaurus v3 现在使用 React 18 "automatic" JSX 运行时

¥Docusaurus v3 now uses the React 18 "automatic" JSX runtime.

不再需要在不使用任何 React API 的 JSX 文件中导入 React。

¥It is not needed anymore to import React in JSX files that do not use any React API.

src/components/MyComponent.js
- import React from 'react';

export default function MyComponent() {
return <div>Hello</div>;
}

ESM 和 TypeScript 配置

¥ESM and TypeScript Configs

Docusaurus v3 支持 ESM 和 TypeScript 配置文件,采用这些新选项可能是个好主意。

¥Docusaurus v3 supports ESM and TypeScript config files, and it might be a good idea to adopt those new options.

docusaurus.config.js
export default {
title: 'Docusaurus',
url: 'https://docusaurus.nodejs.cn',
// your site config ...
};
docusaurus.config.ts
import type {Config} from '@docusaurus/types';
import type * as Preset from '@docusaurus/preset-classic';

const config: Config = {
title: 'My Site',
favicon: 'img/favicon.ico',
presets: [
[
'classic',
{
/* Your preset config here */
} satisfies Preset.Options,
],
],

themeConfig: {
/* Your theme config here */
} satisfies Preset.ThemeConfig,
};

export default config;

使用 .mdx 扩展

¥Using the .mdx extension

每当你在 Markdown 文件中使用 JSX、importexport(即 MDX 功能)时,我们建议使用 .mdx 扩展名。它在语义上更正确,并提高了与外部工具(IDE、格式化程序、linter 等)的兼容性。

¥We recommend using the .mdx extension whenever you use JSX, import, or export (i.e. MDX features) inside a Markdown file. It is semantically more correct and improves compatibility with external tools (IDEs, formatters, linters, etc.).

在 Docusaurus 的未来版本中,.md 文件将被解析为标准 CommonMark,后者不支持这些功能。在 Docusaurus v3 中,.md 文件继续编译为 MDX 文件,但也可以编译为 选择加入 CommonMark

¥In future versions of Docusaurus, .md files will be parsed as standard CommonMark, which does not support these features. In Docusaurus v3, .md files keep being compiled as MDX files, but it will be possible to opt-in for CommonMark.

升级数学包

¥Upgrading math packages

如果你使用 Docusaurus 渲染 数学方程,你应该升级 MDX 插件。

¥If you use Docusaurus to render Math Equations, you should upgrade the MDX plugins.

确保对 Docusaurus v3 使用 remark-math 6rehype-katex 7(使用 MDX v3)。我们不能保证其他版本也能工作。

¥Make sure to use remark-math 6 and rehype-katex 7 for Docusaurus v3 (using MDX v3). We can't guarantee other versions will work.

{
- "remark-math": "^3.0.0",
+ "remark-math": "^6.0.0",
- "rehype-katex": "^5.0.0"
+ "rehype-katex": "^7.0.0"
}

hast-util-is-element 现在在 Docusaurus v3 中是不必要的。如果你已安装它并且不在其他地方使用它,则只需运行 npm uninstall hast-util-is-element 即可将其删除。

¥hast-util-is-element is now unnecessary in Docusaurus v3. If you have installed it and don't use it somewhere else, you can just remove it by running npm uninstall hast-util-is-element.

关闭 MDX v1 兼容性

¥Turn off MDX v1 compat

Docusaurus v3 附带 MDX v1 兼容性选项,默认情况下处于打开状态。

¥Docusaurus v3 comes with MDX v1 compatibility options, that are turned on by default.

docusaurus.config.js
export default {
markdown: {
mdx1Compat: {
comments: true,
admonitions: true,
headingIds: true,
},
},
};

comments 选项

¥comments option

此选项允许在 MDX 中使用 HTML 注释,但官方不再支持 HTML 注释。

¥This option allows the usage of HTML comments inside MDX, while HTML comments are officially not supported anymore.

对于 MDX 文件,我们建议逐步使用 MDX {/* comments */} 而不是 HTML <!-- comments -->,然后关闭此兼容性选项。

¥For MDX files, we recommend to progressively use MDX {/* comments */} instead of HTML <!-- comments -->, and then turn this compatibility option off.

博客截断标记

默认博客截断标记现在支持 <!-- truncate -->{/* truncate */}

¥The default blog truncate marker now supports both <!-- truncate --> and {/* truncate */}.

admonitions 选项

¥admonitions option

此选项允许使用 Docusaurus v2 训诫标题 语法:

¥This option allows the usage of the Docusaurus v2 admonition title syntax:



:::note Your Title



content



:::


Docusaurus 现在使用 Markdown 指令 实现警告(使用 remark-directive 实现),并且提供指令标签的语法需要方括号:

¥Docusaurus now implements admonitions with Markdown Directives (implemented with remark-directive), and the syntax to provide a directive label requires square brackets:



:::note[Your Title]



content



:::


我们建议逐步使用新的 Markdown 指令标签语法,然后关闭此兼容性选项。

¥We recommend to progressively use the new Markdown directive label syntax, and then turn this compatibility option off.

headingIds 选项

¥headingIds option

此选项允许使用 Docusaurus v2 显式标题 ID 语法:

¥This option allows the usage of the Docusaurus v2 explicit heading id syntax:

### Hello World {#my-explicit-id}

此语法现在是无效的 MDX,并且需要转义 { 字符:\{#my-explicit-id}

¥This syntax is now invalid MDX, and would require to escape the { character: \{#my-explicit-id}.

我们建议暂时保留此兼容性选项,直到我们提供与较新版本的 MDX 兼容的新语法。

¥We recommend to keep this compatibility option on for now, until we provide a new syntax compatible with newer versions of MDX.

故障排除

¥Troubleshooting

如果出现任何升级问题,首先要尝试的是:

¥In case of any upgrade problem, the first things to try are:

  • 确保所有文档都在 MDX 在线运行 中编译,或使用 npx docusaurus-mdx-checker

    ¥make sure all your docs compile in the MDX playground, or using npx docusaurus-mdx-checker

  • 删除 node_modulespackage-lock.json,然后再次运行 npm install

    ¥delete node_modules and package-lock.json, and then run npm install again

  • 运行 docusaurus clear 清除缓存

    ¥run docusaurus clear to clear the caches

  • 删除可能不支持 Docusaurus v3 的第三方插件

    ¥remove third-party plugins that might not support Docusaurus v3

  • 删除所有混合的组件

    ¥delete all your swizzled components

尝试后,你可以通过以下支持渠道寻求支持:

¥Once you have tried that, you can ask for support through the following support channels:

请考虑我们的时间是宝贵的。为了确保你的支持请求不被忽视,我们恳请你:

¥Please consider our time is precious. To ensure that your support request is not ignored, we kindly ask you to:

  • 提供我们可以轻松运行的最小复制品,理想情况下使用 docusaurus.new 创建

    ¥provide a minimal reproduction that we can easily run, ideally created with docusaurus.new

  • 提供一个实时部署 URL,显示正在发生的问题(如果你的站点可以构建)

    ¥provide a live deployment url showing the problem in action (if your site can build)

  • 把问题解释清楚,比模棱两可的 "它不起作用" 多得多

    ¥explain clearly the problem, much more than an ambiguous "it doesn't work"

  • 包含尽可能多的相关材料:代码片段、repo url、git 分支 url、完整堆栈跟踪、屏幕截图和视频

    ¥include as much relevant material as possible: code snippets, repo url, git branch urls, full stack traces, screenshots and videos

  • 清楚、简洁地提出你的请求,向我们表明你已尽力帮助我们帮助你

    ¥present your request clearly, concisely, showing us that you have made an effort to help us help you

或者,你可以寻找付费的 Docusaurus 服务提供商 来为你执行此升级。如果你的网站是开源的,你也可以向我们的社区索要 免费的、善意的帮助

¥Alternatively, you can look for a paid Docusaurus Service Provider to execute this upgrade for you. If your site is open source, you can also ask our community for free, benevolent help.