Skip to main content

Main function for a Docusaurus plugin

Yes, the function (context, options) is the main function for a Docusaurus plugin, and it serves as the entry point for the plugin's logic. This function is called by Docusaurus during the site's build process.

Where and When is This Function Called?

  • During the Build Process: When Docusaurus runs (either in development mode with npm run start/yarn start or during a production build with npm run build/yarn build), it loads all configured plugins. For each plugin, Docusaurus calls the main function defined in the plugin's entry file.

  • Arguments Passed:

    • context: An object containing useful information about the environment in which the plugin is running. This can include paths, environment variables, site configuration, and other metadata.
    • options: An object containing options specific to the plugin, typically provided by the user in the docusaurus.config.js file. These options allow you to customize the behavior of the plugin.

Example of the Main Plugin Function

Here's an example of a simple Docusaurus plugin that logs some information during the build process:

module.exports = function (context, options) {
return {
name: 'my-custom-plugin',

// Example: Log the context and options during the build
async loadContent() {
console.log('Context:', context);
console.log('Options:', options);
return null; // Optional: Return any content you want to pass along
},

// Example: Add custom logic when the content is loaded
async contentLoaded({ content, actions }) {
console.log('Content loaded:', content);
// You can use actions to add routes, data, etc.
},

// Other lifecycle methods...
};
};

Lifecycle Methods Within the Plugin Function

Inside the plugin's main function, you can define several lifecycle methods that Docusaurus will call at various stages of the build process:

  • loadContent(): Called early in the build process, allowing the plugin to load or generate content that might be used later in the build. For example, this might involve fetching data from an API or reading files from the filesystem.

  • contentLoaded({ content, actions }): Called after loadContent(), allowing the plugin to perform actions with the loaded content, such as adding routes or creating files.

  • postBuild(): Called after the build is complete, which can be used for tasks like cleaning up, modifying build outputs, or generating additional files.

  • configureWebpack(config, isServer, utils): Allows the plugin to customize the Webpack configuration used by Docusaurus.

Example in docusaurus.config.js

When you add the plugin to docusaurus.config.js, you might configure it like this:

module.exports = {
// Other configurations...

plugins: [
[
path.resolve(__dirname, './src/plugins/my-custom-plugin'),
{
customOption1: 'value1',
customOption2: 'value2',
}
]
],

// Other configurations...
};

In this configuration, the options object passed to the plugin would look like this:

{
customOption1: 'value1',
customOption2: 'value2'
}

Conclusion

The function (context, options) is indeed the main function of a Docusaurus plugin and is called during the site's build process. It acts as the entry point for defining the plugin's behavior, with access to the build context and any user-defined options. Within this function, you can implement various lifecycle methods to interact with and modify the build process, allowing you to customize how Docusaurus generates your site.

In a Docusaurus plugin, the lifecycle methods within the main plugin function allow you to hook into various stages of the build process. Each lifecycle method serves a specific purpose and provides opportunities to extend or customize Docusaurus's behavior. Here's a detailed explanation of each lifecycle method:

1. loadContent()

Purpose:

  • To load or generate any content that the plugin needs. This content is typically used later in the build process.

When It’s Called:

  • Early in the build process, before the content is fully processed by Docusaurus.

Usage Example:

async loadContent() {
// Fetch data from an API or read from a file
const data = await fetch('https://api.example.com/data').then(res => res.json());

// Return the loaded content
return {
myCustomData: data
};
}

Returns:

  • An object containing the data that can be used in other lifecycle methods.

2. contentLoaded({ content, actions })

Purpose:

  • To perform actions with the content that has been loaded in the loadContent() method. This might include creating additional routes, pages, or modifying the build output.

When It’s Called:

  • After loadContent() has been executed and the content is available.

Usage Example:

async contentLoaded({ content, actions }) {
const { createData, addRoute } = actions;

// Example: Create a JSON file from the loaded content
const jsonPath = await createData(
'my-custom-data.json',
JSON.stringify(content.myCustomData)
);

// Example: Add a route for a custom page
addRoute({
path: '/custom-page',
component: '@site/src/pages/CustomPage.jsx', // Path to a custom React component
exact: true
});
}

Arguments:

  • content: The content returned from the loadContent() method.
  • actions: An object with methods to perform actions like createData, addRoute, etc.

3. postBuild()

Purpose:

  • To perform tasks after the site has been built. This can include post-processing the build output or generating additional files.

When It’s Called:

  • After the entire site build process is complete.

Usage Example:

async postBuild({ outDir }) {
// Perform post-build tasks, e.g., copying files, generating reports
console.log(`Build complete. Output directory: ${outDir}`);
}

Arguments:

  • outDir: The directory where the build output is located.

4. configureWebpack(config, isServer, utils)

Purpose:

  • To customize the Webpack configuration used by Docusaurus. This is useful for modifying how assets are processed or adding new plugins to Webpack.

When It’s Called:

  • During the Webpack configuration phase of the build process.

Usage Example:

function configureWebpack(config, isServer, utils) {
return {
...config,
plugins: [
...config.plugins,
// Add custom Webpack plugins or configurations here
]
};
}

Arguments:

  • config: The existing Webpack configuration object.
  • isServer: A boolean indicating whether the build is for the server-side or client-side.
  • utils: Utility functions provided by Docusaurus for working with Webpack.

5. getThemePath()

Purpose:

  • To specify a custom theme path if the plugin includes its own theme components.

When It’s Called:

  • When Docusaurus is setting up the theme.

Usage Example:

function getThemePath() {
return path.resolve(__dirname, './theme');
}

Returns:

  • A path to a custom theme directory.

6. getThemeModules()

Purpose:

  • To specify additional theme modules that should be loaded for the plugin.

When It’s Called:

  • When Docusaurus is setting up the theme.

Usage Example:

function getThemeModules() {
return [
path.resolve(__dirname, './theme/module')
];
}

Returns:

  • An array of paths to theme modules.

Summary

Each lifecycle method in a Docusaurus plugin serves a distinct role in the build process:

  • loadContent(): For loading or generating content.
  • contentLoaded({ content, actions }): For processing loaded content and performing actions like adding routes.
  • postBuild(): For performing tasks after the build is complete.
  • configureWebpack(config, isServer, utils): For customizing the Webpack configuration.
  • getThemePath() and getThemeModules(): For specifying custom theme components and modules.

By leveraging these lifecycle methods, you can extend Docusaurus with custom functionality tailored to your needs.