插件

插件是 Docusaurus 2 网站功能的基本构件模块。每个插件都具有独立的功能。插件可以通过 预设 起作用并发布。

安装插件

插件通常是 npm 软件包,因此你可以像其他 npm 软件包一样使用 npm 安装它们。

npm install --save docusaurus-plugin-name

然后将其添加到站点的 docusaurus.config.js 配置文件中的 plugins 配置项中:

docusaurus.config.js
module.exports = {
// ...
plugins: ['@docusaurus/plugin-content-pages'],
};

Docusaurus 也可以从本地目录加载插件,你可以执行以下操作:

docusaurus.config.js
const path = require('path');
module.exports = {
// ...
plugins: [path.resolve(__dirname, '/path/to/docusaurus-local-plugin')],
};

配置插件

对于最基本的插件用法,你可以仅提供插件名称或插件的绝对路径。

However, plugins can have options specified by wrapping the name and an options object in an array inside your config. This style is usually called Babel Style. 但是,插件可以通过将名称和参数对象包装在配置文件中的数组中来指定选项。这种风格通常称为 Babel 风格

docusaurus.config.js
module.exports = {
// ...
plugins: [
[
'@docusaurus/plugin-xxx',
{
/* options */
},
],
],
};

示例:

docusaurus.config.js
module.exports = {
plugins: [
// Basic usage.
'@docusaurus/plugin-google-analytics',
// With options object (babel style)
[
'@docusaurus/plugin-sitemap',
{
cacheTime: 600 * 1000,
},
],
],
};

插件设计

Docusaurus' implementation of the plugins system provides us with a convenient way to hook into the website's lifecycle to modify what goes on during development/build, which involves (but not limited to) extending the webpack config, modifying the data being loaded and creating new components to be used in a page. Docusaurus对插件系统的实施为我们提供了一种便捷的方法,可以进入网站的生命周期,以修改开发/构建过程中发生的事情,这涉及(但不限于)扩展webpack配置,修改要加载的数据并创建新的页面中使用的组件。

创建插件

A plugin is a module which exports a function that takes two parameters and returns an object when executed. 插件是一个模块,其导出一个带有两个参数的函数,并在执行时返回一个对象。

模块定义

The exported modules for plugins are called with two parameters: context and options and returns a JavaScript object with defining the lifecycle APIs. 导出的插件模块使用两个参数调用:context和options,并返回定义了[lifecycle API](./ lifecycle-apis.md)的JavaScript对象。

docusaurus.config.js
module.exports = function(context, options) {
// ...
return {
name: 'my-docusaurus-plugin',
async loadContent() { ... },
async contentLoaded({content, actions}) { ... },
/* other lifecycle API */
};
};

context

context is plugin-agnostic and the same object will be passed into all plugins used for a Docusaurus website. The context object contains the following fields: “上下文”与插件无关,并且相同的对象将传递到Docusaurus网站使用的所有插件中。 “ context”对象包含以下字段:

interface LoadContext {
siteDir: string;
generatedFilesDir: string;
siteConfig: DocusaurusConfig;
outDir: string;
baseUrl: string;
}

options

options are the second optional parameter when the plugins are used. options are plugin-specific and are specified by users when they use them in docusaurus.config.js. Alternatively, if preset contains the plugin, the preset will then be in charge of passing the correct options into the plugin. It is up to individual plugin to define what options it takes. options是[使用插件时的第二个可选参数](using-plugins.md#configuring-plugins)。选项是特定于插件的,由用户在docusaurus.config.js中使用它们时指定。或者,如果预设包含插件,则预设将负责将正确的选项传递给插件。取决于各个插件来定义所需的选项。

返回值

返回的对象值应实现 生命周期 API

官方插件

此处 是官方插件列表。

@docusaurus/plugin-content-blog

提供 博客 功能,并且是 Docusaurus 的默认博客插件。

安装

npm install --save @docusaurus/plugin-content-blog
tip

如果你已经安装了 @docusaurus/preset-classic,则不需要将其安装为依赖项。也可以通过 classic preset 参数 对其进行配置,而不必像下面这样进行配置。

docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-blog',
{
/**
* Path to data on filesystem relative to site dir.
*/
path: 'blog',
/**
* URL for editing a blog post.
* Example: 'https://github.com/facebook/docusaurus/edit/master/website/blog/'
*/
editUrl:
'https://github.com/facebook/docusaurus/edit/master/website/blog/',
/**
* URL route for the blog section of your site.
* *DO NOT* include a trailing slash.
*/
routeBasePath: 'blog',
include: ['*.md', '*.mdx'],
postsPerPage: 10,
/**
* Theme components used by the blog pages.
*/
blogListComponent: '@theme/BlogListPage',
blogPostComponent: '@theme/BlogPostPage',
blogTagsListComponent: '@theme/BlogTagsListPage',
blogTagsPostsComponent: '@theme/BlogTagsPostsPage',
/**
* Remark and Rehype plugins passed to MDX.
*/
remarkPlugins: [
/* require('remark-math') */
],
rehypePlugins: [],
/**
* Custom Remark and Rehype plugins passed to MDX before
* the default Docusaurus Remark and Rehype plugins.
*/
beforeDefaultRemarkPlugins: [],
beforeDefaultRehypePlugins: [],
/**
* Truncate marker, can be a regex or string.
*/
truncateMarker: /<!--\s*(truncate)\s*-->/,
/**
* Show estimated reading time for the blog post.
*/
showReadingTime: true,
/**
* Blog feed.
* If feedOptions is undefined, no rss feed will be generated.
*/
feedOptions: {
type: '', // required. 'rss' | 'feed' | 'all'
title: '', // default to siteConfig.title
description: '', // default to `${siteConfig.title} Blog`
copyright: '',
language: undefined, // possible values: http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
},
},
],
],
};

@docusaurus/plugin-content-docs

提供了 文档 功能,并且是 Docusaurus 的默认文档插件。

安装

npm install --save @docusaurus/plugin-content-docs
tip

如果你已经安装了 @docusaurus/preset-classic,则不需要将其安装为依赖项。你也可以通过 classic preset 参数 对其进行配置,而不必像下面这样进行配置。

docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-docs',
{
/**
* Path to data on filesystem relative to site dir.
*/
path: 'docs',
/**
* URL for editing a doc in the website repo.
* Example: 'https://github.com/facebook/docusaurus/edit/master/website/'
*/
editUrl: 'https://github.com/facebook/docusaurus/edit/master/website/',
/**
* URL route for the blog section of your site.
* *DO NOT* include a trailing slash.
*/
routeBasePath: 'docs',
homePageId: '_index', // Document id for docs home page.
include: ['**/*.md', '**/*.mdx'], // Extensions to include.
/**
* Path to sidebar configuration for showing a list of markdown pages.
* Warning: will change
*/
sidebarPath: '',
/**
* Theme components used by the docs pages
*/
docLayoutComponent: '@theme/DocPage',
docItemComponent: '@theme/DocItem',
/**
* Remark and Rehype plugins passed to MDX
*/
remarkPlugins: [
/* require('remark-math') */
],
rehypePlugins: [],
/**
* Custom Remark and Rehype plugins passed to MDX before
* the default Docusaurus Remark and Rehype plugins.
*/
beforeDefaultRemarkPlugins: [],
beforeDefaultRehypePlugins: [],
/**
* Whether to display the author who last updated the doc.
*/
showLastUpdateAuthor: false,
/**
* Whether to display the last date the doc was updated.
*/
showLastUpdateTime: false,
},
],
],
};

@docusaurus/plugin-content-pages

Docusaurus 的默认页面(pages)插件。classic 主题自带此插件并具有默认配置。此插件提供了 创建页面(pages) 的功能。

安装

npm install --save @docusaurus/plugin-content-pages
tip

如果你已经安装了 @docusaurus/preset-classic,则不需要将其安装为依赖项。你也可以通过 classic preset 参数 对其进行配置,而不必像下面这样进行配置。

docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-pages',
{
/**
* Path to data on filesystem
* relative to site dir
* components in this directory will be automatically converted to pages
*/
path: 'src/pages',
/**
* URL route for the blog section of your site
* do not include trailing slash
*/
routeBasePath: '',
include: ['**/*.{js,jsx}'],
},
],
],
};

@docusaurus/plugin-google-analytics

默认的 Google Analytics 插件。它是一个 JavaScript 库,用于衡量用户与你的网站的是如何交互的。

安装

npm install --save @docusaurus/plugin-google-analytics
tip

如果你已经安装了 @docusaurus/preset-classic,则不需要将其安装为依赖项。

配置

docusaurus.config.js
module.exports = {
plugins: ['@docusaurus/plugin-google-analytics'],
themeConfig: {
googleAnalytics: {
trackingID: 'UA-141789564-1',
// Optional fields.
anonymizeIP: true, // Should IPs be anonymized?
},
},
};

@docusaurus/plugin-google-gtag

默认的 Global Site Tag (gtag.js) 插件。 它是一个 JavaScript 标记(tagging)框架以及 API,允许你将事件数据发送到 Google Analytics、Google Ads 和 Google Marketing Platform。本节介绍如何配置 Docusaurus 网站以便为 Google Analytics 启用全局网站标记功能。

安装

npm install --save @docusaurus/plugin-google-gtag
tip

如果你已经安装了 @docusaurus/preset-classic,则不需要将其安装为依赖项。

配置

docusaurus.config.js
module.exports = {
plugins: ['@docusaurus/plugin-google-gtag'],
themeConfig: {
gtag: {
trackingID: 'UA-141789564-1',
// Optional fields.
anonymizeIP: true, // Should IPs be anonymized?
},
},
};

@docusaurus/plugin-sitemap

该插件用于为你的网站创建站点地图,以便搜索引擎爬虫可以更准确地对您的网站进行爬取。

安装

npm install --save @docusaurus/plugin-sitemap
tip

如果你已经安装了 @docusaurus/preset-classic,则不需要将其安装为依赖项。你也可以通过 classic preset 参数 对其进行配置,从而无须像下面这样配置:

docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-sitemap',
{
cacheTime: 600 * 1000, // 600 sec - cache purge period
changefreq: 'weekly',
priority: 0.5,
},
],
],
};

@docusaurus/plugin-ideal-image

此 Docusaurus 插件用于为 生产环境构建版本 生成比较理想的图片(响应式、延迟加载和低质量的占位符)。

npm install --save @docusaurus/plugin-ideal-image

修改你的 docusaurus.config.js 配置文件

module.exports = {
...
+ plugins: ['@docusaurus/plugin-ideal-image'],
...
}

用法

该插件仅支持 PNG、GIF 和 JPG 格式。

import Image from '@theme/IdealImage';
import thumbnail from './path/to/img.png';
// your React code
<Image img={thumbnail} />
// or
<Image img={require('./path/to/img.png')} />

参数

参数类型默认值描述
namestringideal-img/[name].[hash:hex:7].[width].[ext]输出文件的文件名模板。
sizesarrayoriginal size指定要使用的所有宽度值。如果指定的宽度超过原始图像的实际宽度,则将使用原始图像的宽度(即,图像不会被放大)
sizeintegeroriginal size指定你希望使用的一种宽度。如果指定的宽度值超过原始图像的实际宽度,则使用图像的原始宽度(即,图像不会被放大)
mininteger作为手动指定 sizes 参数的替代方法,你可以指定 minmaxsteps,然后会自动为你生成所有符合的尺寸。
maxinteger参见上面的 min 参数
stepsinteger4配置在 minmax (包含)之间生成图像数量。
qualityinteger85JPEG 压缩质量

@docusaurus/plugin-client-redirects

Docusaurus Plugin to generate client-side redirects.

This plugin will write additional HTML pages to your static site, that redirects the user to your existing Docusaurus pages with JavaScript.

caution

It is better to use server-side redirects whenever possible.

Before using this plugin, you should look if your hosting provider doesn't offer this feature.

Installation

npm install --save @docusaurus/plugin-client-redirects

Configuration

Main usecase: you have /myDocusaurusPage, and you want to redirect to this page from /myDocusaurusPage.html:

docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-client-redirects',
{
fromExtensions: ['html'],
},
],
],
};

Second usecase: you have /myDocusaurusPage.html, and you want to redirect to this page from /myDocusaurusPage.

docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-client-redirects',
{
toExtensions: ['html'],
},
],
],
};

For custom redirect logic, provide your own createRedirects function.

Let's imagine you change the url of an existing page, you might want to make sure the old url still works:

docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-client-redirects',
{
redirects: [
{
to: '/docs/newDocPath', // string
from: ['/docs/oldDocPathFrom2019', '/docs/legacyDocPathFrom2016'], // string | string[]
},
],
},
],
],
};

It's possible to use a function to create the redirects for each existing path:

docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-client-redirects',
{
createRedirects: function (existingPath) {
if (existingPath === '/docs/newDocPath') {
return ['/docs/oldDocPathFrom2019', '/docs/legacyDocPathFrom2016']; // string | string[]
}
},
},
],
],
};

Finally, it's possible to use all options at the same time:

docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-client-redirects',
{
fromExtensions: ['html', 'htm'],
toExtensions: ['exe', 'zip'],
redirects: [
{
to: '/docs/newDocPath',
from: '/docs/oldDocPath',
},
],
createRedirects: function (existingPath) {
if (existingPath === '/docs/newDocPath2') {
return ['/docs/oldDocPath2'];
}
},
},
],
],
};
Last updated on by wangsai