跳转至主内容
Version: 2.0.0-beta.8

Docusaurus 客户端 API

Docusaurus 提供了客户端 API 助您构建网站。

组件

此可复用的 React 组件将管理您向文档头做出的所有更改。 它接受纯 HTML 标签作为参数,输出也是纯 HTML 标签,且对新手友好。 这是 React Helmet 的封装。

示例用法:

import React from 'react';
import Head from '@docusaurus/Head';

const MySEO = () => (
<Head>
<meta property="og:description" content="My custom description" />
<meta charSet="utf-8" />
<title>我的标题</title>
<link rel="canonical" href="http://mysite.com/example" />
</Head>
);

嵌套或之后使用的组件将覆盖先前的用例:

<Parent>
<Head>
<title>我的标题</title>
<meta name="description" content="Helmet 应用程序" />
</Head>
<Child>
<Head>
<title>嵌套标题</title>
<meta name="description" content="嵌套组件" />
</Head>
</Child>
</Parent>

会输出:

<head>
<title>嵌套标题</title>
<meta name="description" content="嵌套组件" />
</head>

此组件链接到内部页面,同时提供强大的预加载功能。 预加载让用户在使用此组件导航之前预先加载资源。 我们使用 IntersectionObserver 让位于 Viewport 的 <Link> 获取低优先级请求,随后在用户可能导航到请求资源时利用 onMouseOver 事件来触发高优先级请求。

此组件是 react-router 的 <Link> 组件封装,同时添加了一些 Docusaurus 的限定改进。 所有的属性(Props)均将传递至 react-router 的 <Link> 组件。

External links also work, and automatically have these props: target="_blank" rel="noopener noreferrer".

import React from 'react';
import Link from '@docusaurus/Link';

const Page = () => (
<div>
<p>
来看看我的<Link to="/blog">博客</Link>吧!
</p>
<p>
Follow me on <Link to="https://twitter.com/docusaurus">Twitter</Link>!
</p>
</div>
);

to:string

导航的目标位置。 示例: /docs/introduction

<Link to="/courses" />

<Redirect/>

渲染 <Redirect> 组件将导航至新的位置。 新位置将覆盖历史记录栈的现有位置,效果类似服务端重定向(HTTP 3xx)。 您可参阅 React Router 的重定向文档来了解更多可传入的属性。

示例用法:

import React from 'react';
import {Redirect} from '@docusaurus/router';

const Home = () => {
return <Redirect to="/docs/test" />;
};
note

@docusaurus/router 实现了 React Router 且兼容其功能特性。

<BrowserOnly/>

The <BrowserOnly> component permits to render React components only in the browser, after the React app has hydrated.

tip

Use it for integrating with code that can't run in Node.js, because window or document objects are being accessed.

属性

  • children: render function prop returning browser-only JSX. Will not be executed in Node.js
  • fallback (optional): JSX to render on the server (Node.js) and until React hydration completes.

Example with code

import BrowserOnly from '@docusaurus/BrowserOnly';

const MyComponent = () => {
return (
<BrowserOnly>
{() => {
<span>page url = {window.location.href}</span>;
}}
</BrowserOnly>
);
};

Example with a library

import BrowserOnly from '@docusaurus/BrowserOnly';

const MyComponent = (props) => {
return (
<BrowserOnly fallback={<div>Loading...</div>}>
{() => {
const LibComponent = require('some-lib').LibComponent;
return <LibComponent {...props} />;
}}
</BrowserOnly>
);
};

<Interpolate/>

A simple interpolation component for text containing dynamic placeholders.

The placeholders will be replaced with the provided dynamic values and JSX elements of your choice (strings, links, styled elements...).

属性

  • children: text containing interpolation placeholders like {placeholderName}
  • values: object containing interpolation placeholder values
import React from 'react';
import Link from '@docusaurus/Link';
import Interpolate from '@docusaurus/Interpolate';

export default function VisitMyWebsiteMessage() {
return (
<Interpolate
values={{
firstName: 'Sébastien',
website: (
<Link to="https://docusaurus.io" className="my-website-class">
website
</Link>
),
}}>
{'Hello, {firstName}! How are you? Take a look at my {website}'}
</Interpolate>
);
}

<Translate/>

When localizing your site, the <Translate/> component will allow providing translation support to React components, such as your homepage. The <Translate> component supports interpolation.

The translation strings will be extracted from your code with the docusaurus write-translations CLI and create a code.json translation file in website/i18n/<locale>.

note

The <Translate/> props must be hardcoded strings.

Apart the values prop used for interpolation, it is not possible to use variables, or the static extraction wouldn't work.

属性

  • children: untranslated string in the default site locale (can contain interpolation placeholders)
  • id: optional value to use as key in JSON translation files
  • description: optional text to help the translator
  • values: optional object containing interpolation placeholder values

示例

src/pages/index.js
import React from 'react';
import Layout from '@theme/Layout';

import Translate from '@docusaurus/Translate';

export default function Home() {
return (
<Layout>
<h1>
<Translate
id="homepage.title"
description="The homepage welcome message">
Welcome to my website
</Translate>
</h1>
<main>
<Translate values={{firstName: 'Sébastien'}}>
{'Welcome, {firstName}! How are you?'}
</Translate>
</main>
</Layout>
);
}
note

You can even omit a children prop and specify a translation string in your code.json file manually after running the docusaurus write-translations CLI command.

<Translate id="homepage.title" />

钩子函数

useDocusaurusContext

React hook to access Docusaurus Context. Context contains siteConfig object from docusaurus.config.js, and some additional site metadata.

type DocusaurusPluginVersionInformation =
| {readonly type: 'package'; readonly version?: string}
| {readonly type: 'project'}
| {readonly type: 'local'}
| {readonly type: 'synthetic'};

interface DocusaurusSiteMetadata {
readonly docusaurusVersion: string;
readonly siteVersion?: string;
readonly pluginVersions: Record<string, DocusaurusPluginVersionInformation>;
}

interface I18nLocaleConfig {
label: string;
direction: string;
}

interface I18n {
defaultLocale: string;
locales: [string, ...string[]];
currentLocale: string;
localeConfigs: Record<string, I18nLocaleConfig>;
}

interface DocusaurusContext {
siteConfig: DocusaurusConfig;
siteMetadata: DocusaurusSiteMetadata;
globalData: Record<string, unknown>;
i18n: I18n;
codeTranslations: Record<string, string>;
}

示例用法:

import React from 'react';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';

const MyComponent = () => {
const {siteConfig, siteMetadata} = useDocusaurusContext();
return (
<div>
<h1>{siteConfig.title}</h1>
<div>{siteMetadata.siteVersion}</div>
<div>{siteMetadata.docusaurusVersion}</div>
</div>
);
};

useIsBrowser

Returns true when the React app has successfully hydrated in the browser.

caution

Use this hook instead of typeof windows !== 'undefined' in React rendering logic.

The first client-side render output (in the browser) must be exactly the same as the server-side render output (Node.js).

Not following this rule can lead to unexpected hydration behaviors, as described in The Perils of Rehydration.

示例用法:

import React from 'react';
import useIsBrowser from '@docusaurus/useIsBrowser';

const MyComponent = () => {
const isBrowser = useIsBrowser();
return <div>{isBrowser ? 'Client' : 'Server'}</div>;
};

useBaseUrl

React hook to prepend your site baseUrl to a string.

caution

Don't use it for regular links!

The /baseUrl/ prefix is automatically added to all absolute paths by default:

  • Markdown: [link](/my/path) will link to /baseUrl/my/path
  • React: <Link to="/my/path/">link</Link> will link to /baseUrl/my/path

选项

type BaseUrlOptions = {
forcePrependBaseUrl: boolean;
absolute: boolean;
};

示例用法:

import React from 'react';
import useBaseUrl from '@docusaurus/useBaseUrl';

const SomeImage = () => {
const imgSrc = useBaseUrl('/img/myImage.png');
return <img src={imgSrc} />;
};
tip

In most cases, you don't need useBaseUrl.

Prefer a require() call for assets:

<img src={require('@site/static/img/myImage.png').default} />

useBaseUrlUtils

Sometimes useBaseUrl is not good enough. This hook return additional utils related to your site's base url.

  • withBaseUrl: useful if you need to add base urls to multiple urls at once.
import React from 'react';
import {useBaseUrlUtils} from '@docusaurus/useBaseUrl';

const Component = () => {
const urls = ['/a', '/b'];
const {withBaseUrl} = useBaseUrlUtils();
const urlsWithBaseUrl = urls.map(withBaseUrl);
return <div>{/* ... */}</div>;
};

useGlobalData

React hook to access Docusaurus global data created by all the plugins.

Global data is namespaced by plugin name, and plugin id.

信息

Plugin id is only useful when a plugin is used multiple times on the same site. Each plugin instance is able to create its own global data.

type GlobalData = Record<
PluginName,
Record<
PluginId, // "default" by default
any // plugin-specific data
>
>;

示例用法:

import React from 'react';
import useGlobalData from '@docusaurus/useGlobalData';

const MyComponent = () => {
const globalData = useGlobalData();
const myPluginData = globalData['my-plugin']['default'];
return <div>{myPluginData.someAttribute}</div>;
};
tip

Inspect your site's global data at ./docusaurus/globalData.json

usePluginData

Access global data created by a specific plugin instance.

This is the most convenient hook to access plugin global data, and should be used most of the time.

pluginId is optional if you don't use multi-instance plugins.

usePluginData(pluginName: string, pluginId?: string)

示例用法:

import React from 'react';
import {usePluginData} from '@docusaurus/useGlobalData';

const MyComponent = () => {
const myPluginData = usePluginData('my-plugin');
return <div>{myPluginData.someAttribute}</div>;
};

useAllPluginInstancesData

Access global data created by a specific plugin. Given a plugin name, it returns the data of all the plugins instances of that name, by plugin id.

useAllPluginInstancesData(pluginName: string)

示例用法:

import React from 'react';
import {useAllPluginInstancesData} from '@docusaurus/useGlobalData';

const MyComponent = () => {
const allPluginInstancesData = useAllPluginInstancesData('my-plugin');
const myPluginData = allPluginInstancesData['default'];
return <div>{myPluginData.someAttribute}</div>;
};

函数

interpolate

The imperative counterpart of the <Interpolate> component.

Signature

// Simple string interpolation
function interpolate(text: string, values: Record<string, string>): string;

// JSX interpolation
function interpolate(
text: string,
values: Record<string, ReactNode>,
): ReactNode;

示例

import {interpolate} from '@docusaurus/Interpolate';

const message = interpolate('Welcome {firstName}', {firstName: 'Sébastien'});

translate

The imperative counterpart of the <Translate> component. Also supporting placeholders interpolation.

tip

Use the imperative API for the rare cases where a component cannot be used, such as:

  • the page title metadata
  • the placeholder props of form inputs
  • the aria-label props for accessibility

Signature

function translate(
translation: {message: string; id?: string; description?: string},
values: Record<string, string>,
): string;

示例

src/pages/index.js
import React from 'react';
import Layout from '@theme/Layout';

import {translate} from '@docusaurus/Translate';

export default function Home() {
return (
<Layout
title={translate({message: 'My page meta title'})}
>
<img
src={'https://docusaurus.io/logo.png'}
aria-label={
translate(
{
message: 'The logo of site {siteName}',
// Optional
id: 'homepage.logo.ariaLabel',
description: 'The home page logo aria label',
},
{siteName: 'Docusaurus'},
)
}
/>
</Layout>
);
}

模块

ExecutionEnvironment

A module which exposes a few boolean variables to check the current rendering environment.

caution

For React rendering logic, use useIsBrowser() or <BrowserOnly> instead.

示例:

import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';

if (ExecutionEnvironment.canUseDOM) {
require('lib-that-only-works-client-side');
}
字段描述
ExecutionEnvironment.canUseDOMtrue if on client/browser, false on Node.js/prerendering.
ExecutionEnvironment.canUseEventListenerstrue if on client and has window.addEventListener.
ExecutionEnvironment.canUseIntersectionObservertrue if on client and has IntersectionObserver.
ExecutionEnvironment.canUseViewporttrue if on client and has window.screen.

constants

A module exposing useful constants to client-side theme code.

import {DEFAULT_PLUGIN_ID} from '@docusaurus/constants';
Named exportValue
DEFAULT_PLUGIN_IDdefault