Aller au contenu principal
Version: 3.0.0-rc.1

Cycle de vie des API

Pendant la construction, les plugins sont chargés en parallèle pour récupérer leur propre contenu et les rendre aux routes. Les plugins peuvent également configurer webpack ou post-traiter les fichiers générés.

async loadContent()

Plugins should use this lifecycle to fetch from data sources (filesystem, remote API, headless CMS, etc.) or do some server processing. La valeur retournée est le contenu dont il a besoin.

Par exemple, ce plugin ci-dessous renvoie un entier aléatoire compris entre 1 et 10 comme contenu.

docusaurus-plugin/src/index.js
export default function (context, options) {
return {
name: 'docusaurus-plugin',
async loadContent() {
return 1 + Math.floor(Math.random() * 10);
},
};
}

async contentLoaded({content, actions})

The data that was loaded in loadContent will be consumed in contentLoaded. Il peut être rendu sur des routes, enregistrés en tant que données globales, etc.

content

contentLoaded will be called after loadContent is done. The return value of loadContent() will be passed to contentLoaded as content.

actions

actions contain three functions:

addRoute(config: RouteConfig): void

Créez une route pour l'ajouter au site web.

type RouteConfig = {
path: string;
component: string;
modules?: RouteModules;
routes?: RouteConfig[];
exact?: boolean;
priority?: number;
};
type RouteModules = {
[module: string]: Module | RouteModules | RouteModules[];
};
type Module =
| {
path: string;
__import?: boolean;
query?: ParsedUrlQueryInput;
}
| string;

createData(name: string, data: any): Promise<string>

Une callback déclarative pour créer des données statiques (généralement JSON ou string) qui peuvent être fournies ultérieurement à vos routes comme props. Prend le nom du fichier et les données à stocker, et renvoie le chemin du fichier de données actuel.

For example, this plugin below creates a /friends page which displays Your friends are: Yangshun, Sebastien:

website/src/components/Friends.js
import React from 'react';

export default function FriendsComponent({friends}) {
return <div>Your friends are {friends.join(',')}</div>;
}
docusaurus-friends-plugin/src/index.js
export default function friendsPlugin(context, options) {
return {
name: 'docusaurus-friends-plugin',
async contentLoaded({content, actions}) {
const {createData, addRoute} = actions;
// Create friends.json
const friends = ['Yangshun', 'Sebastien'];
const friendsJsonPath = await createData(
'friends.json',
JSON.stringify(friends),
);

// Add the '/friends' routes, and ensure it receives the friends props
addRoute({
path: '/friends',
component: '@site/src/components/Friends.js',
modules: {
// propName -> JSON file path
friends: friendsJsonPath,
},
exact: true,
});
},
};
}

setGlobalData(data: any): void

Cette fonction permet de créer des données globales de plugin, qui peuvent être lues depuis n'importe quelle page, y compris les pages créées par d'autres plugins et la mise en page de votre thème.

This data becomes accessible to your client-side/theme code through the useGlobalData and usePluginData hooks.

attention

Global data is... global: its size affects the loading time of all pages of your site, so try to keep it small. Prefer createData and page-specific data whenever possible.

For example, this plugin below creates a /friends page which displays Your friends are: Yangshun, Sebastien:

website/src/components/Friends.js
import React from 'react';
import {usePluginData} from '@docusaurus/useGlobalData';

export default function FriendsComponent() {
const {friends} = usePluginData('docusaurus-friends-plugin');
return <div>Your friends are {friends.join(',')}</div>;
}
docusaurus-friends-plugin/src/index.js
export default function friendsPlugin(context, options) {
return {
name: 'docusaurus-friends-plugin',
async contentLoaded({content, actions}) {
const {setGlobalData, addRoute} = actions;
// Crée des données globales friends
setGlobalData({friends: ['Yangshun', 'Sebastien']});

// Ajoute la route '/friends'
addRoute({
path: '/friends',
component: '@site/src/components/Friends.js',
exact: true,
});
},
};
}

configureWebpack(config, isServer, utils, content)

Modifie la configuration interne de webpack. If the return value is a JavaScript object, it will be merged into the final config using webpack-merge. If it is a function, it will be called and receive config as the first argument and an isServer flag as the second argument.

attention

The API of configureWebpack will be modified in the future to accept an object (configureWebpack({config, isServer, utils, content}))

config

configureWebpack is called with config generated according to client/server build. Vous pouvez le considérer comme la configuration de base avec laquelle il faut fusionner.

isServer

configureWebpack will be called both in server build and in client build. The server build receives true and the client build receives false as isServer.

utils

configureWebpack also receives an util object:

  • getStyleLoaders(isServer: boolean, cssOptions: {[key: string]: any}): Loader[]
  • getJSLoader(isServer: boolean, cacheOptions?: {}): Loader | null

Vous pouvez les utiliser pour retourner votre configuration webpack sous certaines conditions.

For example, this plugin below modify the webpack config to transpile .foo files.

docusaurus-plugin/src/index.js
export default function (context, options) {
return {
name: 'custom-docusaurus-plugin',
configureWebpack(config, isServer, utils) {
const {getJSLoader} = utils;
return {
module: {
rules: [
{
test: /\.foo$/,
use: [getJSLoader(isServer), 'my-custom-webpack-loader'],
},
],
},
};
},
};
}

content

configureWebpack will be called both with the content loaded by the plugin.

Merge strategy

We merge the Webpack configuration parts of plugins into the global Webpack config using webpack-merge.

Il est possible de spécifier la stratégie de fusion. Par exemple, si vous voulez qu'une règle de webpack soit placée au début au lieu d'être ajoutée à la fin :

docusaurus-plugin/src/index.js
export default function (context, options) {
return {
name: 'custom-docusaurus-plugin',
configureWebpack(config, isServer, utils) {
return {
mergeStrategy: {'module.rules': 'prepend'},
module: {rules: [myRuleToPrepend]},
};
},
};
}

Read the webpack-merge strategy doc for more details.

Configuring dev server

The dev server can be configured through returning a devServer field.

docusaurus-plugin/src/index.js
export default function (context, options) {
return {
name: 'custom-docusaurus-plugin',
configureWebpack(config, isServer, utils) {
return {
devServer: {
open: '/docs', // Ouvre localhost:3000/docs au lieu de localhost:3000/
},
};
},
};
}

configurePostCss(options)

Modifies postcssOptions of postcss-loader during the generation of the client bundle.

Should return the mutated postcssOptions.

By default, postcssOptions looks like this:

const postcssOptions = {
ident: 'postcss',
plugins: [require('autoprefixer')],
};

Exemple :

docusaurus-plugin/src/index.js
export default function (context, options) {
return {
name: 'docusaurus-plugin',
configurePostCss(postcssOptions) {
// Appends new PostCSS plugin.
postcssOptions.plugins.push(require('postcss-import'));
return postcssOptions;
},
};
}

postBuild(props)

Appelée quand une version (production) se termine.

interface Props {
siteDir: string;
generatedFilesDir: string;
siteConfig: DocusaurusConfig;
outDir: string;
baseUrl: string;
headTags: string;
preBodyTags: string;
postBodyTags: string;
routesPaths: string[];
plugins: Plugin<any>[];
content: Content;
}

Exemple :

docusaurus-plugin/src/index.js
export default function (context, options) {
return {
name: 'docusaurus-plugin',
async postBuild({siteConfig = {}, routesPaths = [], outDir}) {
// Print out to console all the rendered routes.
routesPaths.map((route) => {
console.log(route);
});
},
};
}

injectHtmlTags({content})

Injecte les balises HTML head et/ou body vers le HTML générées de Docusaurus.

injectHtmlTags will be called both with the content loaded by the plugin.

function injectHtmlTags(): {
headTags?: HtmlTags;
preBodyTags?: HtmlTags;
postBodyTags?: HtmlTags;
};

type HtmlTags = string | HtmlTagObject | (string | HtmlTagObject)[];

type HtmlTagObject = {
/**
* Attributes of the HTML tag
* E.g. `{'disabled': true, 'value': 'demo', 'rel': 'preconnect'}`
*/
attributes?: {
[attributeName: string]: string | boolean;
};
/**
* The tag name e.g. `div`, `script`, `link`, `meta`
*/
tagName: string;
/**
* The inner HTML
*/
innerHTML?: string;
};

Exemple :

docusaurus-plugin/src/index.js
export default function (context, options) {
return {
name: 'docusaurus-plugin',
loadContent: async () => {
return {remoteHeadTags: await fetchHeadTagsFromAPI()};
},
injectHtmlTags({content}) {
return {
headTags: [
{
tagName: 'link',
attributes: {
rel: 'preconnect',
href: 'https://www.github.com',
},
},
...content.remoteHeadTags,
],
preBodyTags: [
{
tagName: 'script',
attributes: {
charset: 'utf-8',
src: '/noflash.js',
},
},
],
postBodyTags: [`<div> This is post body </div>`],
};
},
};
}

Les balises seront ajoutés comme ceci:

  • headTags will be inserted before the closing </head> tag after scripts added by config.
  • preBodyTags will be inserted after the opening <body> tag before any child elements.
  • postBodyTags will be inserted before the closing </body> tag after all child elements.

getClientModules()

Returns an array of paths to the client modules that are to be imported into the client bundle.

As an example, to make your theme load a customCss or customJs file path from options passed in by the user:

my-theme/src/index.js
export default function (context, options) {
const {customCss, customJs} = options || {};
return {
name: 'name-of-my-theme',
getClientModules() {
return [customCss, customJs];
},
};
}