跳到主要内容
版本:3.9.1

docusaurus.config.js

信息

Refer to the Getting Started Configuration for examples.

Overview

docusaurus.config.js contains configurations for your site and is placed in the root directory of your site.

备注

With a TypeScript Docusaurus codebase your config file may be called docusaurus.config.ts. The syntax is broadly identical to the js config file with the addition of types. You can see an example on the Docusaurus Website itself.

This file is run in Node.js and should export a site configuration object, or a function that creates it.

The docusaurus.config.js file supports:

示例:

docusaurus.config.js
export default {
title: 'Docusaurus',
url: 'https://docusaurus.io',
// your site config ...
};
docusaurus.config.js
export default async function createConfigAsync() {
return {
title: 'Docusaurus',
url: 'https://docusaurus.io',
// your site config ...
};
}
提示

Refer to Syntax to declare docusaurus.config.js for a more exhaustive list of examples and explanations.

Required fields

title

  • Type: string

网站标题。 会用于页面元数据中,以及浏览器选项卡标题。

docusaurus.config.js
export default {
title: 'Docusaurus',
};

url

  • Type: string

网站网址。 你可以把它看作是顶级主机名。 For example, https://facebook.github.io is the URL of https://facebook.github.io/metro/, and https://docusaurus.io is the URL for https://docusaurus.io. This field is related to the baseUrl field.

docusaurus.config.js
export default {
url: 'https://docusaurus.io',
};
Special case for i18n sites

If your site uses multiple locales, it is possible to provide a distinct url for each locale thanks to the siteConfig.i18n.localeConfigs[<locale>].url attribute. This makes it possible to deploy a localized Docusaurus site deploy a localized Docusaurus site over multiple domains.

baseUrl

  • Type: string

The base URL of your site is the path segment appearing just after the url, letting you eventually host your site under a subpath instead of at the root of the domain.

For example, let's consider you want to host a site at https://facebook.github.io/metro/, then you must configure it accordingly:

  • url should be 'https://facebook.github.io'
  • baseUrl should be '/metro/'

By default, a Docusaurus site is hosted at the root of the domain:

docusaurus.config.js
export default {
baseUrl: '/',
};
Special case for i18n sites

If your site uses multiple locales, then Docusaurus will automatically localize the baseUrl of your site based on smart heuristics:

  • For the default locale, baseUrl will be /<siteBaseUrl>/
  • For other locales, baseUrl will be /<siteBaseUrl>/<locale>/
  • When building a single locale at a time (with docusaurus build --locale <locale>), baseUrl will be /<siteBaseUrl>/, assuming the intent is to deploy each locale on distinct domains.

When the localized baseUrl Docusaurus computes doesn't satisfy you, it's always possible to override it by providing an explicit localized baseUrl thanks to the siteConfig.i18n.localeConfigs[<locale>].baseUrl attribute.

Optional fields

favicon

  • Type: string | undefined

你的网站图标的路径;必须是可以用于链接 href 的 URL。 For example, if your favicon is in static/img/favicon.ico:

docusaurus.config.js
export default {
favicon: '/img/favicon.ico',
};

trailingSlash

  • Type: boolean | undefined

这个选项允许你自定义 URL/链接后是否添加末尾斜杠,以及静态 HTML 会如何被生成。

  • undefined (default): keeps URLs untouched, and emit /docs/myDoc/index.html for /docs/myDoc.md
  • true: add trailing slashes to URLs/links, and emit /docs/myDoc/index.html for /docs/myDoc.md
  • false: remove trailing slashes from URLs/links, and emit /docs/myDoc.html for /docs/myDoc.md
提示

每个静态托管服务商在提供静态文件时的表现都有不同(甚至可能随着时间的推移而改变)。

Refer to the deployment guide and slorber/trailing-slash-guide to choose the appropriate setting.

i18n

  • Type: Object

The i18n configuration object to localize your site.

示例:

docusaurus.config.js
export default {
i18n: {
defaultLocale: 'en',
locales: ['en', 'fa'],
path: 'i18n',
localeConfigs: {
en: {
label: 'English',
direction: 'ltr',
htmlLang: 'en-US',
calendar: 'gregory',
path: 'en',
translate: false,
url: 'https://en.example.com',
baseUrl: '/',
},
fa: {
label: 'فارسی',
direction: 'rtl',
htmlLang: 'fa-IR',
calendar: 'persian',
path: 'fa',
translate: true,
url: 'https://fa.example.com',
baseUrl: '/',
},
},
},
};
  • defaultLocale: The locale that (1) does not have its name in the base URL (2) gets started with docusaurus start without --locale option (3) will be used for the <link hrefLang="x-default"> tag
  • locales: List of locales deployed on your site. Must contain defaultLocale.
  • path: Root folder which all locale folders are relative to. 路径可以是绝对的,或者相对于配置文件。 Defaults to i18n.
  • localeConfigs: Individual options for each locale.
    • label: The label displayed for this locale in the locales dropdown.
    • direction: ltr (default) or rtl (for right-to-left languages like Farsi, Arabic, Hebrew, etc.). 用于选择语言的 CSS 和 HTML 元属性。
    • htmlLang: BCP 47 language tag to use in <html lang="..."> (or any other DOM tag name) and in <link ... hreflang="...">
    • calendar: the calendar used to calculate the date era. Note that it doesn't control the actual string displayed: MM/DD/YYYY and DD/MM/YYYY are both gregory. To choose the format (DD/MM/YYYY or MM/DD/YYYY), set your locale name to en-GB or en-US (en means en-US).
    • path: Root folder that all plugin localization folders of this locale are relative to. Will be resolved against i18n.path. Defaults to the locale's name (i18n/<locale>). Note: this has no effect on the locale's baseUrl—customization of base URL is a work-in-progress.
    • translate: Should we run the translation process for this locale? By default, it is enabled if the i18n/<locale> folder exists
    • url: This lets you override the siteConfig.url, particularly useful if your site is deployed over multiple domains.
    • baseUrl: This lets you override the default localized baseUrl Docusaurus infers from your siteConfig.baseUrl, giving you more control to host your localized site in less common ways, in particularly deployments over multi-domains

future

  • Type: Object

The future configuration object permits to opt-in for upcoming/unstable/experimental Docusaurus features that are not ready for prime time.

它也是一种选择即将到来的重大版本中的重大变更的方法,使你可以在保持当前版本的同时为下一个版本做好准备。 The Remix Future Flags blog post greatly explains this idea.

Breaking changes in minor versions

Features prefixed by experimental_ or unstable_ are subject to changes in minor versions, and not considered as Semantic Versioning breaking changes.

Features namespaced by v<MajorVersion> (v6 v7, etc.) are future flags that are expected to be turned on by default in the next major versions. These are less likely to change, but we keep the possibility to do so.

future API breaking changes should be easy to handle, and will be documented in minor/major version blog posts.

示例:

docusaurus.config.js
export default {
future: {
v4: {
removeLegacyPostBuildHeadAttribute: true,
useCssCascadeLayers: true,
},
experimental_faster: {
swcJsLoader: true,
swcJsMinimizer: true,
swcHtmlMinimizer: true,
lightningCssMinimizer: true,
rspackBundler: true,
rspackPersistentCache: true,
ssgWorkerThreads: true,
mdxCrossCompilerCache: true,
},
experimental_storage: {
type: 'localStorage',
namespace: true,
},
experimental_router: 'hash',
},
};
  • v4: Permits to opt-in for upcoming Docusaurus v4 breaking changes and features, to prepare your site in advance for this new version. Use true as a shorthand to enable all the flags.
  • experimental_faster: An object containing feature flags to make the Docusaurus build faster. This requires adding the @docusaurus/faster package to your site's dependencies. Use true as a shorthand to enable all flags. Read more on the Docusaurus Faster issue. Available feature flags:
  • experimental_storage: Site-wide browser storage options that theme authors should strive to respect.
    • type: The browser storage theme authors should use. Possible values are localStorage and sessionStorage. Defaults to localStorage.
    • namespace: Whether to namespace the browser storage keys to avoid storage key conflicts when Docusaurus sites are hosted under the same domain, or on localhost. Possible values are string | boolean. The namespace is appended at the end of the storage keys key-namespace. Use true to automatically generate a random namespace from your site url + baseUrl. Defaults to false (no namespace, historical behavior).
  • experimental_router: The router type to use. Possible values are browser and hash. Defaults to browser. The hash router is only useful for rare cases where you want to opt-out of static site generation, have a fully client-side app with a single index.html entrypoint file. This can be useful to distribute a Docusaurus site as a .zip archive that you can browse locally without running a web server.

noIndex

  • Type: boolean

This option adds <meta name="robots" content="noindex, nofollow"> to every page to tell search engines to avoid indexing your site (more information here).

示例:

docusaurus.config.js
export default {
noIndex: true, // 默认为 `false`
};
  • Type: 'ignore' | 'log' | 'warn' | 'throw'

Docusaurus 在检测到无效链接时的行为。

默认情况下,它会产生一个错误,以确保您永远不会上传任何已失效链接。

备注

The broken links detection is only available for a production build (docusaurus build).

onBrokenAnchors

  • Type: 'ignore' | 'log' | 'warn' | 'throw'

The behavior of Docusaurus when it detects any broken anchor declared with the Heading component of Docusaurus.

默认情况下,它会打印警告,让您知道无效的锚点。

Deprecated

Deprecated in Docusaurus v3.9, and will be removed in Docusaurus v4.

Replaced by siteConfig.markdown.hooks.onBrokenMarkdownLinks

  • Type: 'ignore' | 'log' | 'warn' | 'throw'

Docusaurus 在检测到无效 Markdown 链接时的行为。

默认情况下,它会打印警告,让您知道您已损坏的Markdown链接。

onDuplicateRoutes

  • Type: 'ignore' | 'log' | 'warn' | 'throw'

The behavior of Docusaurus when it detects any duplicate routes.

By default, it displays a warning after you run yarn start or yarn build.

tagline

  • Type: string

网站标语。

docusaurus.config.js
export default {
tagline:
'Docusaurus 让维护开源文档站点更加轻松。',
};

organizationName

  • Type: string

拥有这个仓库的 GitHub 用户或组织。 You don't need this if you are not using the docusaurus deploy command.

docusaurus.config.js
export default {
// Docusaurus 的所属组织是 facebook
organizationName: 'facebook',
};

projectName

  • Type: string

GitHub 仓库的名称。 You don't need this if you are not using the docusaurus deploy command.

docusaurus.config.js
export default {
projectName: 'docusaurus',
};

deploymentBranch

  • Type: string

要把静态文件部署到的分支名称。 You don't need this if you are not using the docusaurus deploy command.

docusaurus.config.js
export default {
deploymentBranch: 'gh-pages',
};

githubHost

  • Type: string

GitHub 服务器的主机名。 适用于 GitHub Enterprise。 You don't need this if you are not using the docusaurus deploy command.

docusaurus.config.js
export default {
githubHost: 'github.com',
};

githubPort

  • Type: string

服务器端口。 适用于 GitHub Enterprise。 You don't need this if you are not using the docusaurus deploy command.

docusaurus.config.js
export default {
githubPort: '22',
};

themeConfig

  • Type: Object

The theme configuration object to customize your site UI like navbar and footer.

示例:

docusaurus.config.js
export default {
themeConfig: {
docs: {
sidebar: {
hideable: false,
autoCollapseCategories: false,
},
},
colorMode: {
defaultMode: 'light',
disableSwitch: false,
respectPrefersColorScheme: true,
},
navbar: {
title: 'Site Title',
logo: {
alt: 'Site Logo',
src: 'img/logo.svg',
width: 32,
height: 32,
},
items: [
{
to: 'docs/docusaurus.config.js',
activeBasePath: 'docs',
label: 'docusaurus.config.js',
position: 'left',
},
// ... other links
],
},
footer: {
style: 'dark',
links: [
{
title: 'Docs',
items: [
{
label: 'Docs',
to: 'docs/doc1',
},
],
},
// ... other links
],
logo: {
alt: 'Meta Open Source Logo',
src: 'img/meta_oss_logo.png',
href: 'https://opensource.fb.com',
width: 160,
height: 51,
},
copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`, // You can also put own HTML here
},
},
};

plugins

  • Type: PluginConfig[]
type PluginConfig = string | [string, any] | PluginModule | [PluginModule, any];

See plugin method references for the shape of a PluginModule.

docusaurus.config.js
export default {
plugins: [
'docusaurus-plugin-awesome',
['docusuarus-plugin-confetti', {fancy: false}],
() => ({
postBuild() {
console.log('Build finished');
},
}),
],
};

themes

  • Type: PluginConfig[]
docusaurus.config.js
export default {
themes: ['@docusaurus/theme-classic'],
};

presets

  • Type: PresetConfig[]
type PresetConfig = string | [string, any];
docusaurus.config.js
export default {
presets: [],
};

markdown

Docusaurus 中 Markdown 的全局配置。

  • Type: MarkdownConfig
type MarkdownPreprocessor = (args: {
filePath: string;
fileContent: string;
}) => string;

type MDX1CompatOptions =
| boolean
| {
comments: boolean;
admonitions: boolean;
headingIds: boolean;
};

export type ParseFrontMatter = (params: {
filePath: string;
fileContent: string;
defaultParseFrontMatter: ParseFrontMatter;
}) => Promise<{
frontMatter: {[key: string]: unknown};
content: string;
}>;

type MarkdownAnchorsConfig = {
maintainCase: boolean;
};

type OnBrokenMarkdownLinksFunction = (params: {
sourceFilePath: string; // MD/MDX source file relative to cwd
url: string; // Link url
node: Link | Definition; // mdast Node
}) => void | string;

type OnBrokenMarkdownImagesFunction = (params: {
sourceFilePath: string; // MD/MDX source file relative to cwd
url: string; // Image url
node: Image; // mdast node
}) => void | string;

type ReportingSeverity = 'ignore' | 'log' | 'warn' | 'throw';

type MarkdownHooks = {
onBrokenMarkdownLinks: ReportingSeverity | OnBrokenMarkdownLinksFunction;
onBrokenMarkdownImages: ReportingSeverity | OnBrokenMarkdownImagesFunction;
};

type MarkdownConfig = {
format: 'mdx' | 'md' | 'detect';
mermaid: boolean;
emoji: boolean;
preprocessor?: MarkdownPreprocessor;
parseFrontMatter?: ParseFrontMatter;
mdx1Compat: MDX1CompatOptions;
remarkRehypeOptions: object; // see https://github.com/remarkjs/remark-rehype#options
anchors: MarkdownAnchorsConfig;
hooks: MarkdownHooks;
};

示例:

docusaurus.config.js
export default {
markdown: {
format: 'mdx',
mermaid: true,
emoji: true,
preprocessor: ({filePath, fileContent}) => {
return fileContent.replaceAll('{{MY_VAR}}', 'MY_VALUE');
},
parseFrontMatter: async (params) => {
const result = await params.defaultParseFrontMatter(params);
result.frontMatter.description =
result.frontMatter.description?.replaceAll('{{MY_VAR}}', 'MY_VALUE');
return result;
},
mdx1Compat: {
comments: true,
admonitions: true,
headingIds: true,
},
anchors: {
maintainCase: true,
},
hooks: {
onBrokenMarkdownLinks: 'warn',
onBrokenMarkdownImages: 'throw',
},
},
};
参数类型默认值描述
format'mdx' | 'md' | 'detect''mdx'用于Markdown内容的默认解析器格式。 Using 'detect' will select the appropriate format automatically based on file extensions: .md vs .mdx.
mermaidbooleanfalseWhen true, allows Docusaurus to render Markdown code blocks with mermaid language as Mermaid diagrams.
emojibooleantrueWhen true, allows Docusaurus to render emoji shortcodes (e.g., :+1:) as Unicode emoji (👍). When false, emoji shortcodes are left as-is.
preprocessorMarkdownPreprocessorundefinedGives you the ability to alter the Markdown content string before parsing. Use it as a last-resort escape hatch or workaround: it is almost always better to implement a Remark/Rehype plugin.
parseFrontMatterParseFrontMatterundefinedGives you the ability to provide your own front matter parser, or to enhance the default parser. Read our front matter guide for details.
mdx1CompatMDX1CompatOptions{comments: true, admonitions: true, headingIds: true}兼容性选项让它更容易升级到 Docusaurus v3+。
anchorsMarkdownAnchorsConfig{maintainCase: false}Options to control the behavior of anchors generated from Markdown headings
remarkRehypeOptionsobjectundefinedMakes it possible to pass custom remark-rehype options.
hooksMarkdownHooksobjectMake it possible to customize the MDX loader behavior with callbacks or built-in options.

customFields

Docusaurus guards docusaurus.config.js from unknown fields. To add a custom field, define it on customFields.

  • Type: Object
docusaurus.config.js
export default {
customFields: {
admin: 'endi',
superman: 'lol',
},
};

试图在配置中添加未知字段会导致构建时错误:

Error: The field(s) 'foo', 'bar' are not recognized in docusaurus.config.js

staticDirectories

An array of paths, relative to the site's directory or absolute. Files under these paths will be copied to the build output as-is.

  • Type: string[]

示例:

docusaurus.config.js
export default {
staticDirectories: ['static'],
};

headTags

An array of tags that will be inserted in the HTML <head>. The values must be objects that contain two properties; tagName and attributes. tagName must be a string that determines the tag being created; eg "link". attributes must be an attribute-value map.

  • Type: { tagName: string; attributes: Object; }[]

示例:

docusaurus.config.js
export default {
headTags: [
{
tagName: 'link',
attributes: {
rel: 'icon',
href: '/img/docusaurus.png',
},
},
],
};

This would become <link rel="icon" href="img/docusaurus.png" /> in the generated HTML.

scripts

一组要加载的脚本。 每个值可以是字符串,或是属性到值的对象映射表。 The <script> tags will be inserted in the HTML <head>. If you use a plain object, the only required attribute is src, and any other attributes are permitted (each one should have boolean/string values).

Note that <script> added here are render-blocking, so you might want to add async: true/defer: true to the objects.

  • Type: (string | Object)[]

示例:

docusaurus.config.js
export default {
scripts: [
// String format.
'https://docusaurus.io/script.js',
// Object format.
{
src: 'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js',
async: true,
},
],
};

stylesheets

一组要加载的 CSS 源。 每个值可以是字符串,或是属性到值的对象映射表。 The <link> tags will be inserted in the HTML <head>. If you use an object, the only required attribute is href, and any other attributes are permitted (each one should have boolean/string values).

  • Type: (string | Object)[]

示例:

docusaurus.config.js
export default {
stylesheets: [
// String format.
'https://docusaurus.io/style.css',
// Object format.
{
href: 'http://mydomain.com/style.css',
},
],
};
信息

By default, the <link> tags will have rel="stylesheet", but you can explicitly add a custom rel value to inject any kind of <link> tag, not necessarily stylesheets.

clientModules

An array of client modules to load globally on your site.

示例:

docusaurus.config.js
export default {
clientModules: ['./mySiteGlobalJs.js', './mySiteGlobalCss.css'],
};

ssrTemplate

An HTML template written in Eta's syntax that will be used to render your application. This can be used to set custom attributes on the body tags, additional meta tags, customize the viewport, etc. 请注意,Docusaurus 需要此模板的结构完全正确才能正常工作。修改之后,你需要确保你的模板与上游的要求一致。

  • Type: string

示例:

docusaurus.config.js
export default {
ssrTemplate: `<!DOCTYPE html>
<html <%~ it.htmlAttributes %>>
<head>
<meta charset="UTF-8">
<meta name="generator" content="Docusaurus v<%= it.version %>">
<% it.metaAttributes.forEach((metaAttribute) => { %>
<%~ metaAttribute %>
<% }); %>
<%~ it.headTags %>
<% it.stylesheets.forEach((stylesheet) => { %>
<link rel="stylesheet" href="<%= it.baseUrl %><%= stylesheet %>" />
<% }); %>
<% it.scripts.forEach((script) => { %>
<link rel="preload" href="<%= it.baseUrl %><%= script %>" as="script">
<% }); %>
</head>
<body <%~ it.bodyAttributes %>>
<%~ it.preBodyTags %>
<div id="__docusaurus">
<%~ it.appHtml %>
</div>
<% it.scripts.forEach((script) => { %>
<script src="<%= it.baseUrl %><%= script %>"></script>
<% }); %>
<%~ it.postBodyTags %>
</body>
</html>`,
};

titleDelimiter

  • Type: string

Will be used as title delimiter in the generated <title> tag.

示例:

docusaurus.config.js
export default {
titleDelimiter: '🦖', // 默认为 `|`
};

baseUrlIssueBanner

  • Type: boolean

When enabled, will show a banner in case your site can't load its CSS or JavaScript files, which is a very common issue, often related to a wrong baseUrl in site config.

示例:

docusaurus.config.js
export default {
baseUrlIssueBanner: true, // 默认为 `true`
};

A sample base URL issue banner. 样式非常粗糙,因为样式表加载失败了。 The text says &quot;Your Docusaurus site did not load properly... Current configured baseUrl = / (default value); We suggest trying baseUrl = /build/

警告

这个横幅需要内联 CSS / JS,以防所有资源都因错误的 base URL 而加载失败。

If you have a strict Content Security Policy, you should rather disable it.