mirror of
https://github.com/facebook/docusaurus.git
synced 2025-05-18 19:46:57 +02:00
docs: create Docusaurus v2.4.1 release docs + changelog (#8980)
This commit is contained in:
parent
8b109342c8
commit
ec3cb1f67d
95 changed files with 38 additions and 1 deletions
|
@ -0,0 +1,146 @@
|
|||
# Plugin Method References
|
||||
|
||||
:::caution
|
||||
|
||||
This section is a work in progress. Anchor links or even URLs are not guaranteed to be stable.
|
||||
|
||||
:::
|
||||
|
||||
Plugin APIs are shared by themes and plugins—themes are loaded just like plugins.
|
||||
|
||||
## Plugin module {#plugin-module}
|
||||
|
||||
Every plugin is imported as a module. The module is expected to have the following members:
|
||||
|
||||
- A **default export**: the constructor function for the plugin.
|
||||
- **Named exports**: the [static methods](./static-methods.mdx) called before plugins are initialized.
|
||||
|
||||
## Plugin constructor {#plugin-constructor}
|
||||
|
||||
The plugin module's default export is a constructor function with the signature `(context: LoadContext, options: PluginOptions) => Plugin | Promise<Plugin>`.
|
||||
|
||||
### `context` {#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:
|
||||
|
||||
```ts
|
||||
type LoadContext = {
|
||||
siteDir: string;
|
||||
generatedFilesDir: string;
|
||||
siteConfig: DocusaurusConfig;
|
||||
outDir: string;
|
||||
baseUrl: string;
|
||||
};
|
||||
```
|
||||
|
||||
### `options` {#options}
|
||||
|
||||
`options` are the [second optional parameter when the plugins are used](../../using-plugins.mdx#configuring-plugins). `options` are plugin-specific and are specified by users when they use them in `docusaurus.config.js`. If there's a [`validateOptions`](./static-methods.mdx#validateOptions) function exported, the `options` will be validated and normalized beforehand.
|
||||
|
||||
Alternatively, if a preset contains the plugin, the preset will then be in charge of passing the correct options into the plugin. It is up to the individual plugin to define what options it takes.
|
||||
|
||||
## Example {#example}
|
||||
|
||||
Here's a mental model for a presumptuous plugin implementation.
|
||||
|
||||
```js
|
||||
// A JavaScript function that returns an object.
|
||||
// `context` is provided by Docusaurus. Example: siteConfig can be accessed from context.
|
||||
// `opts` is the user-defined options.
|
||||
async function myPlugin(context, opts) {
|
||||
return {
|
||||
// A compulsory field used as the namespace for directories to cache
|
||||
// the intermediate data for each plugin.
|
||||
// If you're writing your own local plugin, you will want it to
|
||||
// be unique in order not to potentially conflict with imported plugins.
|
||||
// A good way will be to add your own project name within.
|
||||
name: 'docusaurus-my-project-cool-plugin',
|
||||
|
||||
async loadContent() {
|
||||
// The loadContent hook is executed after siteConfig and env has been loaded.
|
||||
// You can return a JavaScript object that will be passed to contentLoaded hook.
|
||||
},
|
||||
|
||||
async contentLoaded({content, actions}) {
|
||||
// The contentLoaded hook is done after loadContent hook is done.
|
||||
// `actions` are set of functional API provided by Docusaurus (e.g. addRoute)
|
||||
},
|
||||
|
||||
async postBuild(props) {
|
||||
// After docusaurus <build> finish.
|
||||
},
|
||||
|
||||
// TODO
|
||||
async postStart(props) {
|
||||
// docusaurus <start> finish
|
||||
},
|
||||
|
||||
// TODO
|
||||
afterDevServer(app, server) {
|
||||
// https://webpack.js.org/configuration/dev-server/#devserverbefore
|
||||
},
|
||||
|
||||
// TODO
|
||||
beforeDevServer(app, server) {
|
||||
// https://webpack.js.org/configuration/dev-server/#devserverafter
|
||||
},
|
||||
|
||||
configureWebpack(config, isServer, utils, content) {
|
||||
// Modify internal webpack config. If returned value is an Object, it
|
||||
// will be merged into the final config using webpack-merge;
|
||||
// If the returned value is a function, it will receive the config as the 1st argument and an isServer flag as the 2nd argument.
|
||||
},
|
||||
|
||||
getPathsToWatch() {
|
||||
// Paths to watch.
|
||||
},
|
||||
|
||||
getThemePath() {
|
||||
// Returns the path to the directory where the theme components can
|
||||
// be found.
|
||||
},
|
||||
|
||||
getClientModules() {
|
||||
// Return an array of paths to the modules that are to be imported
|
||||
// in the client bundle. These modules are imported globally before
|
||||
// React even renders the initial UI.
|
||||
},
|
||||
|
||||
extendCli(cli) {
|
||||
// Register an extra command to enhance the CLI of Docusaurus
|
||||
},
|
||||
|
||||
injectHtmlTags({content}) {
|
||||
// Inject head and/or body HTML tags.
|
||||
},
|
||||
|
||||
async getTranslationFiles({content}) {
|
||||
// Return translation files
|
||||
},
|
||||
|
||||
translateContent({content, translationFiles}) {
|
||||
// translate the plugin content here
|
||||
},
|
||||
|
||||
translateThemeConfig({themeConfig, translationFiles}) {
|
||||
// translate the site themeConfig here
|
||||
},
|
||||
|
||||
async getDefaultCodeTranslationMessages() {
|
||||
// return default theme translations here
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
myPlugin.validateOptions = ({options, validate}) => {
|
||||
const validatedOptions = validate(myValidationSchema, options);
|
||||
return validatedOptions;
|
||||
};
|
||||
|
||||
myPlugin.validateThemeConfig = ({themeConfig, validate}) => {
|
||||
const validatedThemeConfig = validate(myValidationSchema, options);
|
||||
return validatedThemeConfig;
|
||||
};
|
||||
|
||||
module.exports = myPlugin;
|
||||
```
|
|
@ -0,0 +1,2 @@
|
|||
label: Plugin method references
|
||||
position: 1
|
|
@ -0,0 +1,135 @@
|
|||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Extending infrastructure
|
||||
|
||||
Docusaurus has some infrastructure like hot reloading, CLI, and swizzling, that can be extended by external plugins.
|
||||
|
||||
## `getPathsToWatch()` {#getPathsToWatch}
|
||||
|
||||
Specifies the paths to watch for plugins and themes. The paths are watched by the dev server so that the plugin lifecycles are reloaded when contents in the watched paths change. Note that the plugins and themes modules are initially called with `context` and `options` from Node, which you may use to find the necessary directory information about the site.
|
||||
|
||||
Use this for files that are consumed server-side, because theme files are automatically watched by Webpack dev server.
|
||||
|
||||
Example:
|
||||
|
||||
```js title="docusaurus-plugin/src/index.js"
|
||||
const path = require('path');
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'docusaurus-plugin',
|
||||
// highlight-start
|
||||
getPathsToWatch() {
|
||||
const contentPath = path.resolve(context.siteDir, options.path);
|
||||
return [`${contentPath}/**/*.{ts,tsx}`];
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## `extendCli(cli)` {#extendCli}
|
||||
|
||||
Register an extra command to enhance the CLI of Docusaurus. `cli` is a [commander](https://www.npmjs.com/package/commander/v/5.1.0) object.
|
||||
|
||||
:::caution
|
||||
|
||||
The commander version matters! We use commander v5, and make sure you are referring to the right version documentation for available APIs.
|
||||
|
||||
:::
|
||||
|
||||
Example:
|
||||
|
||||
```js title="docusaurus-plugin/src/index.js"
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'docusaurus-plugin',
|
||||
// highlight-start
|
||||
extendCli(cli) {
|
||||
cli
|
||||
.command('roll')
|
||||
.description('Roll a random number between 1 and 1000')
|
||||
.action(() => {
|
||||
console.log(Math.floor(Math.random() * 1000 + 1));
|
||||
});
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## `getThemePath()` {#getThemePath}
|
||||
|
||||
Returns the path to the directory where the theme components can be found. When your users call `swizzle`, `getThemePath` is called and its returned path is used to find your theme components. Relative paths are resolved against the folder containing the entry point.
|
||||
|
||||
For example, your `getThemePath` can be:
|
||||
|
||||
```js title="my-theme/src/index.js"
|
||||
const path = require('path');
|
||||
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'my-theme',
|
||||
// highlight-start
|
||||
getThemePath() {
|
||||
return './theme';
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## `getTypeScriptThemePath()` {#getTypeScriptThemePath}
|
||||
|
||||
Similar to `getThemePath()`, it should return the path to the directory where the source code of TypeScript theme components can be found. This path is purely for swizzling TypeScript theme components, and theme components under this path will **not** be resolved by Webpack. Therefore, it is not a replacement for `getThemePath()`. Typically, you can make the path returned by `getTypeScriptThemePath()` be your source directory, and make the path returned by `getThemePath()` be the compiled JavaScript output.
|
||||
|
||||
:::tip
|
||||
|
||||
For TypeScript theme authors: you are strongly advised to make your compiled output as human-readable as possible. Only strip type annotations and don't transpile any syntaxes, because they will be handled by Webpack's Babel loader based on the targeted browser versions.
|
||||
|
||||
You should also format these files with Prettier. Remember—JS files can and will be directly consumed by your users.
|
||||
|
||||
:::
|
||||
|
||||
Example:
|
||||
|
||||
```js title="my-theme/src/index.js"
|
||||
const path = require('path');
|
||||
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'my-theme',
|
||||
// highlight-start
|
||||
getThemePath() {
|
||||
// Where compiled JavaScript output lives
|
||||
return '../lib/theme';
|
||||
},
|
||||
getTypeScriptThemePath() {
|
||||
// Where TypeScript source code lives
|
||||
return '../src/theme';
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## `getSwizzleComponentList()` {#getSwizzleComponentList}
|
||||
|
||||
**This is a static method, not attached to any plugin instance.**
|
||||
|
||||
Returns a list of stable components that are considered safe for swizzling. These components will be swizzlable without `--danger`. All components are considered unstable by default. If an empty array is returned, all components are considered unstable. If `undefined` is returned, all components are considered stable.
|
||||
|
||||
```js title="my-theme/src/index.js"
|
||||
const swizzleAllowedComponents = [
|
||||
'CodeBlock',
|
||||
'DocSidebar',
|
||||
'Footer',
|
||||
'NotFound',
|
||||
'SearchBar',
|
||||
'hooks/useTheme',
|
||||
'prism-include-languages',
|
||||
];
|
||||
|
||||
myTheme.getSwizzleComponentList = () => swizzleAllowedComponents;
|
||||
```
|
|
@ -0,0 +1,121 @@
|
|||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# I18n lifecycles
|
||||
|
||||
Plugins use these lifecycles to load i18n-related data.
|
||||
|
||||
## `getTranslationFiles({content})` {#getTranslationFiles}
|
||||
|
||||
Plugins declare the JSON translation files they want to use.
|
||||
|
||||
Returns translation files `{path: string, content: ChromeI18nJSON}`:
|
||||
|
||||
- `path`: relative to the plugin localized folder `i18n/[locale]/[pluginName]`. Extension `.json` should be omitted to remain generic.
|
||||
- `content`: using the Chrome i18n JSON format.
|
||||
|
||||
These files will be written by the [`write-translations` CLI](../../cli.mdx#docusaurus-write-translations-sitedir) to the plugin i18n subfolder, and will be read in the appropriate locale before calling [`translateContent()`](#translateContent) and [`translateThemeConfig()`](#translateThemeConfig)
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'my-plugin',
|
||||
// highlight-start
|
||||
async getTranslationFiles({content}) {
|
||||
return [
|
||||
{
|
||||
path: 'sidebar-labels',
|
||||
content: {
|
||||
someSidebarLabel: {
|
||||
message: 'Some Sidebar Label',
|
||||
description: 'A label used in my plugin in the sidebar',
|
||||
},
|
||||
someLabelFromContent: content.myLabel,
|
||||
},
|
||||
},
|
||||
];
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## `translateContent({content,translationFiles})` {#translateContent}
|
||||
|
||||
Translate the plugin content, using the localized translation files.
|
||||
|
||||
Returns the localized plugin content.
|
||||
|
||||
The `contentLoaded()` lifecycle will be called with the localized plugin content returned by `translateContent()`.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'my-plugin',
|
||||
// highlight-start
|
||||
translateContent({content, translationFiles}) {
|
||||
const myTranslationFile = translationFiles.find(
|
||||
(f) => f.path === 'myTranslationFile',
|
||||
);
|
||||
return {
|
||||
...content,
|
||||
someContentLabel: myTranslationFile.someContentLabel.message,
|
||||
};
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## `translateThemeConfig({themeConfig,translationFiles})` {#translateThemeConfig}
|
||||
|
||||
Translate the site `themeConfig` labels, using the localized translation files.
|
||||
|
||||
Returns the localized `themeConfig`.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'my-theme',
|
||||
// highlight-start
|
||||
translateThemeConfig({themeConfig, translationFiles}) {
|
||||
const myTranslationFile = translationFiles.find(
|
||||
(f) => f.path === 'myTranslationFile',
|
||||
);
|
||||
return {
|
||||
...themeConfig,
|
||||
someThemeConfigLabel: myTranslationFile.someThemeConfigLabel.message,
|
||||
};
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## `async getDefaultCodeTranslationMessages()` {#getDefaultCodeTranslationMessages}
|
||||
|
||||
Themes using the `<Translate>` API can provide default code translation messages.
|
||||
|
||||
It should return messages in `Record<string, string>`, where keys are translation IDs and values are messages (without the description) localized using the site's current locale.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'my-theme',
|
||||
// highlight-start
|
||||
async getDefaultCodeTranslationMessages() {
|
||||
return readJsonFile(`${context.i18n.currentLocale}.json`);
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
|
@ -0,0 +1,420 @@
|
|||
---
|
||||
sidebar_position: 1
|
||||
toc_max_heading_level: 4
|
||||
---
|
||||
|
||||
# Lifecycle APIs
|
||||
|
||||
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()` {#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.
|
||||
|
||||
```js title="docusaurus-plugin/src/index.js"
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'docusaurus-plugin',
|
||||
// highlight-start
|
||||
async loadContent() {
|
||||
return 1 + Math.floor(Math.random() * 10);
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## `async contentLoaded({content, actions})` {#contentLoaded}
|
||||
|
||||
The data that was loaded in `loadContent` will be consumed in `contentLoaded`. It can be rendered to routes, registered as global data, etc.
|
||||
|
||||
### `content` {#content}
|
||||
|
||||
`contentLoaded` will be called _after_ `loadContent` is done. The return value of `loadContent()` will be passed to `contentLoaded` as `content`.
|
||||
|
||||
### `actions` {#actions}
|
||||
|
||||
`actions` contain three functions:
|
||||
|
||||
#### `addRoute(config: RouteConfig): void` {#addRoute}
|
||||
|
||||
Create a route to add to the website.
|
||||
|
||||
```ts
|
||||
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>` {#createData}
|
||||
|
||||
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`:
|
||||
|
||||
```jsx title="website/src/components/Friends.js"
|
||||
import React from 'react';
|
||||
|
||||
export default function FriendsComponent({friends}) {
|
||||
return <div>Your friends are {friends.join(',')}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
```js title="docusaurus-friends-plugin/src/index.js"
|
||||
export default function friendsPlugin(context, options) {
|
||||
return {
|
||||
name: 'docusaurus-friends-plugin',
|
||||
// highlight-start
|
||||
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,
|
||||
});
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
#### `setGlobalData(data: any): void` {#setGlobalData}
|
||||
|
||||
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`](../../docusaurus-core.mdx#useGlobalData) and [`usePluginData`](../../docusaurus-core.mdx#usePluginData) hooks.
|
||||
|
||||
:::caution
|
||||
|
||||
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`:
|
||||
|
||||
```jsx title="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>;
|
||||
}
|
||||
```
|
||||
|
||||
```js title="docusaurus-friends-plugin/src/index.js"
|
||||
export default function friendsPlugin(context, options) {
|
||||
return {
|
||||
name: 'docusaurus-friends-plugin',
|
||||
// highlight-start
|
||||
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,
|
||||
});
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## `configureWebpack(config, isServer, utils, content)` {#configureWebpack}
|
||||
|
||||
Modifies the internal webpack config. If the return value is a JavaScript object, it will be merged into the final config using [`webpack-merge`](https://github.com/survivejs/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.
|
||||
|
||||
:::caution
|
||||
|
||||
The API of `configureWebpack` will be modified in the future to accept an object (`configureWebpack({config, isServer, utils, content})`)
|
||||
|
||||
:::
|
||||
|
||||
### `config` {#config}
|
||||
|
||||
`configureWebpack` is called with `config` generated according to client/server build. You may treat this as the base config to be merged with.
|
||||
|
||||
### `isServer` {#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` {#utils}
|
||||
|
||||
`configureWebpack` also receives an util object:
|
||||
|
||||
- `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.
|
||||
|
||||
```js title="docusaurus-plugin/src/index.js"
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'custom-docusaurus-plugin',
|
||||
// highlight-start
|
||||
configureWebpack(config, isServer, utils) {
|
||||
const {getJSLoader} = utils;
|
||||
return {
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.foo$/,
|
||||
use: [getJSLoader(isServer), 'my-custom-webpack-loader'],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
### `content` {#content-1}
|
||||
|
||||
`configureWebpack` will be called both with the content loaded by the plugin.
|
||||
|
||||
### Merge strategy {#merge-strategy}
|
||||
|
||||
We merge the Webpack configuration parts of plugins into the global Webpack config using [webpack-merge](https://github.com/survivejs/webpack-merge).
|
||||
|
||||
It is possible to specify the merge strategy. For example, if you want a webpack rule to be prepended instead of appended:
|
||||
|
||||
```js title="docusaurus-plugin/src/index.js"
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'custom-docusaurus-plugin',
|
||||
configureWebpack(config, isServer, utils) {
|
||||
return {
|
||||
// highlight-start
|
||||
mergeStrategy: {'module.rules': 'prepend'},
|
||||
module: {rules: [myRuleToPrepend]},
|
||||
// highlight-end
|
||||
};
|
||||
},
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Read the [webpack-merge strategy doc](https://github.com/survivejs/webpack-merge#merging-with-strategies) for more details.
|
||||
|
||||
### Configuring dev server {#configuring-dev-server}
|
||||
|
||||
The dev server can be configured through returning a `devServer` field.
|
||||
|
||||
```js title="docusaurus-plugin/src/index.js"
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'custom-docusaurus-plugin',
|
||||
configureWebpack(config, isServer, utils) {
|
||||
return {
|
||||
// highlight-start
|
||||
devServer: {
|
||||
open: '/docs', // Opens localhost:3000/docs instead of localhost:3000/
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
},
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## `configurePostCss(options)` {#configurePostCss}
|
||||
|
||||
Modifies [`postcssOptions` of `postcss-loader`](https://webpack.js.org/loaders/postcss-loader/#postcssoptions) during the generation of the client bundle.
|
||||
|
||||
Should return the mutated `postcssOptions`.
|
||||
|
||||
By default, `postcssOptions` looks like this:
|
||||
|
||||
```js
|
||||
const postcssOptions = {
|
||||
ident: 'postcss',
|
||||
plugins: [require('autoprefixer')],
|
||||
};
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```js title="docusaurus-plugin/src/index.js"
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'docusaurus-plugin',
|
||||
// highlight-start
|
||||
configurePostCss(postcssOptions) {
|
||||
// Appends new PostCSS plugin.
|
||||
postcssOptions.plugins.push(require('postcss-import'));
|
||||
return postcssOptions;
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## `postBuild(props)` {#postBuild}
|
||||
|
||||
Called when a (production) build finishes.
|
||||
|
||||
```ts
|
||||
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;
|
||||
}
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```js title="docusaurus-plugin/src/index.js"
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'docusaurus-plugin',
|
||||
// highlight-start
|
||||
async postBuild({siteConfig = {}, routesPaths = [], outDir}) {
|
||||
// Print out to console all the rendered routes.
|
||||
routesPaths.map((route) => {
|
||||
console.log(route);
|
||||
});
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## `injectHtmlTags({content})` {#injectHtmlTags}
|
||||
|
||||
Inject head and/or body HTML tags to Docusaurus generated HTML.
|
||||
|
||||
`injectHtmlTags` will be called both with the content loaded by the plugin.
|
||||
|
||||
```ts
|
||||
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;
|
||||
};
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```js title="docusaurus-plugin/src/index.js"
|
||||
module.exports = function (context, options) {
|
||||
return {
|
||||
name: 'docusaurus-plugin',
|
||||
loadContent: async () => {
|
||||
return {remoteHeadTags: await fetchHeadTagsFromAPI()};
|
||||
},
|
||||
// highlight-start
|
||||
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>`],
|
||||
};
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## `getClientModules()` {#getClientModules}
|
||||
|
||||
Returns an array of paths to the [client modules](../../advanced/client.mdx#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:
|
||||
|
||||
```js title="my-theme/src/index.js"
|
||||
const path = require('path');
|
||||
|
||||
module.exports = function (context, options) {
|
||||
const {customCss, customJs} = options || {};
|
||||
return {
|
||||
name: 'name-of-my-theme',
|
||||
// highlight-start
|
||||
getClientModules() {
|
||||
return [customCss, customJs];
|
||||
},
|
||||
// highlight-end
|
||||
};
|
||||
};
|
||||
```
|
|
@ -0,0 +1,123 @@
|
|||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Static methods
|
||||
|
||||
Static methods are not part of the plugin instance—they are attached to the constructor function. These methods are used to validate and normalize the plugin options and theme config, which are then used as constructor parameters to initialize the plugin instance.
|
||||
|
||||
## `validateOptions({options, validate})` {#validateOptions}
|
||||
|
||||
Returns validated and normalized options for the plugin. This method is called before the plugin is initialized. You must return the options since they will be passed to the plugin during initialization.
|
||||
|
||||
### `options` {#options}
|
||||
|
||||
`validateOptions` is called with `options` passed to plugin for validation and normalization.
|
||||
|
||||
### `validate` {#validate}
|
||||
|
||||
`validateOptions` is called with `validate` function which takes a **[Joi](https://www.npmjs.com/package/joi)** schema and options as the arguments, returns validated and normalized options. `validate` will automatically handle error and validation config.
|
||||
|
||||
:::tip
|
||||
|
||||
[Joi](https://www.npmjs.com/package/joi) is recommended for validation and normalization of options.
|
||||
|
||||
To avoid mixing Joi versions, use `const {Joi} = require("@docusaurus/utils-validation")`
|
||||
|
||||
:::
|
||||
|
||||
If you don't use **[Joi](https://www.npmjs.com/package/joi)** for validation you can throw an Error in case of invalid options and return options in case of success.
|
||||
|
||||
```js title="my-plugin/src/index.js"
|
||||
function myPlugin(context, options) {
|
||||
return {
|
||||
name: 'docusaurus-plugin',
|
||||
// rest of methods
|
||||
};
|
||||
}
|
||||
|
||||
// highlight-start
|
||||
myPlugin.validateOptions = ({options, validate}) => {
|
||||
const validatedOptions = validate(myValidationSchema, options);
|
||||
return validatedOptions;
|
||||
};
|
||||
// highlight-end
|
||||
|
||||
module.exports = myPlugin;
|
||||
```
|
||||
|
||||
In TypeScript, you can also choose to export this as a separate named export.
|
||||
|
||||
```ts title="my-plugin/src/index.ts"
|
||||
export default function (context, options) {
|
||||
return {
|
||||
name: 'docusaurus-plugin',
|
||||
// rest of methods
|
||||
};
|
||||
}
|
||||
|
||||
// highlight-start
|
||||
export function validateOptions({options, validate}) {
|
||||
const validatedOptions = validate(myValidationSchema, options);
|
||||
return validatedOptions;
|
||||
}
|
||||
// highlight-end
|
||||
```
|
||||
|
||||
## `validateThemeConfig({themeConfig, validate})` {#validateThemeConfig}
|
||||
|
||||
Return validated and normalized configuration for the theme.
|
||||
|
||||
### `themeConfig` {#themeConfig}
|
||||
|
||||
`validateThemeConfig` is called with `themeConfig` provided in `docusaurus.config.js` for validation and normalization.
|
||||
|
||||
### `validate` {#validate-1}
|
||||
|
||||
`validateThemeConfig` is called with `validate` function which takes a **[Joi](https://www.npmjs.com/package/joi)** schema and `themeConfig` as the arguments, returns validated and normalized options. `validate` will automatically handle error and validation config.
|
||||
|
||||
:::tip
|
||||
|
||||
[Joi](https://www.npmjs.com/package/joi) is recommended for validation and normalization of theme config.
|
||||
|
||||
To avoid mixing Joi versions, use `const {Joi} = require("@docusaurus/utils-validation")`
|
||||
|
||||
:::
|
||||
|
||||
If you don't use **[Joi](https://www.npmjs.com/package/joi)** for validation you can throw an Error in case of invalid options.
|
||||
|
||||
```js title="my-theme/src/index.js"
|
||||
function myPlugin(context, options) {
|
||||
return {
|
||||
name: 'docusaurus-plugin',
|
||||
// rest of methods
|
||||
};
|
||||
}
|
||||
|
||||
// highlight-start
|
||||
myPlugin.validateThemeConfig = ({themeConfig, validate}) => {
|
||||
const validatedThemeConfig = validate(myValidationSchema, options);
|
||||
return validatedThemeConfig;
|
||||
};
|
||||
// highlight-end
|
||||
|
||||
module.exports = validateThemeConfig;
|
||||
```
|
||||
|
||||
In TypeScript, you can also choose to export this as a separate named export.
|
||||
|
||||
```ts title="my-theme/src/index.ts"
|
||||
export default function (context, options) {
|
||||
return {
|
||||
name: 'docusaurus-plugin',
|
||||
// rest of methods
|
||||
};
|
||||
}
|
||||
|
||||
// highlight-start
|
||||
export function validateThemeConfig({themeConfig, validate}) {
|
||||
const validatedThemeConfig = validate(myValidationSchema, options);
|
||||
return validatedThemeConfig;
|
||||
}
|
||||
// highlight-end
|
||||
```
|
Loading…
Add table
Add a link
Reference in a new issue