Pular para o conteúdo principal
Version: 2.3.1

APIs de ciclo de vida

During the build, plugins are loaded in parallel to fetch their own contents and render them to routes. Plugins may also configure webpack or post-process the generated files.

async loadContent()

Plugins should use this lifecycle to fetch from data sources (filesystem, remote API, headless CMS, etc.) or do some server processing. The return value is the content it needs.

For example, this plugin below returns a random integer between 1 to 10 as content.

docusaurus-plugin/src/index.js
module.exports = 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. It can be rendered to routes, registered as global data, 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

Criar uma rota para adicionar ao site.

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>

A declarative callback to create static data (generally JSON or string) which can later be provided to your routes as props. Takes the file name and data to be stored, and returns the actual data file's path.

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

This function permits one to create some global plugin data that can be read from any page, including the pages created by other plugins, and your theme layout.

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

warning

Dados globais são... globais: seu tamanho afeta o tempo de carregamento de todas as páginas de seu site, então tente mantê-los pequenos. Prefira createData e dados específicos da página sempre que possível.

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;
// Create friends global data
setGlobalData({friends: ['Yangshun', 'Sebastien']});

// Add the '/friends' routes
addRoute({
path: '/friends',
component: '@site/src/components/Friends.js',
exact: true,
});
},
};
}

configureWebpack(config, isServer, utils, content)

Modifica a configuração interna do webpack. Se o valor de retorno for um objeto JavaScript, ele será mesclado na configuração final usando 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.

warning

A API de configureWebpack será modificada no futuro para aceitar um objeto (configureWebpack({config, isServer, utils, content})

config

configureWebpack é chamado com config gerada de acordo com compilação de cliente/servidor. Você pode tratar isto como a configuração base a ser mesclada.

isServer

configureWebpack será chamado tanto em compilação de servidor quanto na compilação do cliente. A compilação do servidor recebe true e a compilação do cliente recebe false como isServer.

utils

configureWebpack também recebe um objeto util:

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

You may use them to return your webpack configuration conditionally.

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

docusaurus-plugin/src/index.js
module.exports = 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 será chamado com o conteúdo carregado pelo plugin.

Estratégia de merge

Mesclamos as partes de configuração dos plugins na configuração global do Webpack usando webpack-merge.

É possível especificar a estratégia de mesclagem. Por exemplo, se você quer que uma regra webpack seja anexada em vez de adicionada:

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

Leia o ponto de estratégia de mesclagem web para mais detalhes.

Configuring dev server

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

docusaurus-plugin/src/index.js
module.exports = function (context, options) {
return {
name: 'custom-docusaurus-plugin',
configureWebpack(config, isServer, utils) {
return {
devServer: {
open: '/docs', // Opens localhost:3000/docs instead of localhost:3000/
},
};
},
};
};

configurePostCss(options)

Modifica postcssOptions de postcss-loader durante a geração do pacote para clientes.

Deve retornar as postcssOptions modificadas.

Por padrão, as postcssOptions se parecem com isso:

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

Exemplo:

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

postBuild(props)

Chamada quando termina a compilação de (produção).

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;
}

Exemplo:

docusaurus-plugin/src/index.js
module.exports = 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})

Injete a cabeça e/ou as tags HTML do Docusaurus no HTML.

injectHtmlTags será chamado de ambos com o conteúdo carregado pelo 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;
};

Exemplo:

docusaurus-plugin/src/index.js
module.exports = 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>`],
};
},
};
};

getClientModules()

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

Como exemplo, para fazer com que seu tema carregue um caminho de arquivo customCss ou customJs das opções passadas pelo usuário:

my-theme/src/index.js
const path = require('path');

module.exports = function (context, options) {
const {customCss, customJs} = options || {};
return {
name: 'name-of-my-theme',
getClientModules() {
return [customCss, customJs];
},
};
};