跳到主要内容
版本:2.4.3

静态方法

静态方法不是插件实例的一部分——它们是构造器函数的一部分。 这些方法会被用来校验并规范化插件选项和主题配置,而后两者随后会作为构造器参数用来初始化插件实例。

validateOptions({options, validate})

返回已校验和规范化的插件选项。 这个方法会在插件被初始化前被调用。 你必须返回新选项,因为这个选项会在初始化时被传递给插件。

options

validateOptions is called with options passed to plugin for validation and normalization.

validate

validateOptions is called with validate function which takes a Joi schema and options as the arguments, returns validated and normalized options. validate will automatically handle error and validation config.

提示

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 for validation you can throw an Error in case of invalid options and return options in case of success.

my-plugin/src/index.js
function myPlugin(context, options) {
return {
name: 'docusaurus-plugin',
// rest of methods
};
}

myPlugin.validateOptions = ({options, validate}) => {
const validatedOptions = validate(myValidationSchema, options);
return validatedOptions;
};

module.exports = myPlugin;

在 TypeScript 中,你也可以选择把这个函数作为单独的命名导出。

my-plugin/src/index.ts
export default function (context, options) {
return {
name: 'docusaurus-plugin',
// rest of methods
};
}

export function validateOptions({options, validate}) {
const validatedOptions = validate(myValidationSchema, options);
return validatedOptions;
}

validateThemeConfig({themeConfig, validate})

返回已校验和规范化的主题配置。

themeConfig

validateThemeConfig is called with themeConfig provided in docusaurus.config.js for validation and normalization.

validate

validateThemeConfig is called with validate function which takes a Joi schema and themeConfig as the arguments, returns validated and normalized options. validate will automatically handle error and validation config.

提示

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 for validation you can throw an Error in case of invalid options.

my-theme/src/index.js
function myPlugin(context, options) {
return {
name: 'docusaurus-plugin',
// rest of methods
};
}

myPlugin.validateThemeConfig = ({themeConfig, validate}) => {
const validatedThemeConfig = validate(myValidationSchema, options);
return validatedThemeConfig;
};

module.exports = validateThemeConfig;

在 TypeScript 中,你也可以选择把这个函数作为单独的命名导出。

my-theme/src/index.ts
export default function (context, options) {
return {
name: 'docusaurus-plugin',
// 其余的方法
};
}

export function validateThemeConfig({themeConfig, validate}) {
const validatedThemeConfig = validate(myValidationSchema, options);
return validatedThemeConfig;
}