插件
插件是 Docusaurus 2 功能特性的基石。 每个插件都有其自己的独立功能。 插件可打包在预设中进行分发。
#
可用插件#
安装插件插件通常为 npm 软件包,所以您可以像其他 npm 包一样使用 npm 安装。
- npm
- Yarn
npm install --save docusaurus-plugin-name
yarn add docusaurus-plugin-name
然后,您需要将其添加到站点中 docusaurus.config.js
的 plugins
选项:
module.exports = { // ... plugins: ['@docusaurus/plugin-content-pages'],};
Docusaurus 也可从您的本地目录加载插件,您需要添加如下示例代码:
const path = require('path');
module.exports = { // ... plugins: [path.resolve(__dirname, '/path/to/docusaurus-local-plugin')],};
#
配置插件最简单的插件用法,是提供插件名称或插件的绝对路径。
但是,插件可能需要包裹名称及设置对象来指定选项。 这种风格通常称作 Babel Style
。
module.exports = { // ... plugins: [ [ '@docusaurus/plugin-xxx', { /* 选项 */ }, ], ],};
Example:
module.exports = { plugins: [ // 基础用法 '@docusaurus/plugin-google-analytics',
// 携带设置对象(babel style) [ '@docusaurus/plugin-sitemap', { changefreq: 'weekly', }, ], ],};
#
多实例插件及插件 ID所有的 Docusaurus 内容插件都可支持多个插件实例。
文档插件则有额外的多实例文档。
您需要为每个插件实例分配唯一的 ID。
默认情况下,插件 ID 为 default
。
module.exports = { plugins: [ [ '@docusaurus/plugin-xxx', { id: 'plugin-xxx-1', // 其他设置 }, ], [ '@docusaurus/plugin-xxx', { id: 'plugin-xxx-2', // 其他设置 }, ], ],};
note
仅有一个插件实例可作为 "默认插件实例"。您可缺省 id
属性或使用 id: 'default'
来将其设为默认。
#
插件设计Docusaurus 的插件系统实现可让您轻松 Hook 进网站的生命周期来更改开发/构建时的行为,包括但不限于扩展 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.
For example if you have a reference to a local folder such as this in your docusaurus.config.js
:
module.exports = { // ... plugins: [path.resolve(__dirname, 'my-plugin')],};
Then in the folder my-plugin
you can create an index.js such as this
module.exports = function (context, options) { // ... return { name: 'my-docusaurus-plugin', async loadContent() { /* ... */ }, async contentLoaded({content, actions}) { /* ... */ }, /* other lifecycle API */ };};
The my-plugin
folder could also be a fully fledged package with it's own package.json and a src/index.js
file for example
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:
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.
#
返回值The returned object value should implement the lifecycle APIs.