close
  • English
  • Write a plugin

    This example injects a global component to show how to define and use plugins.

    1. Define a plugin

    plugin.ts
    import type { RspressPlugin } from '@rspress/core';
    
    export function pluginExample(slug: string): RspressPlugin {
      // Component path. You need to implement the component yourself.
      const componentPath = path.join(__dirname, 'Example.tsx');
      return {
        name: 'plugin-example',
        // Path to global components
        globalUIComponents: [componentPath],
        // Global variable definitions for build phase
        builderConfig: {
          source: {
            define: {
              'process.env.SLUG': JSON.stringify(slug),
            },
          },
        },
      };
    }
    Example.tsx
    import React from 'react';
    
    const Example = () => {
      console.log(process.env.SLUG);
      return <div>Example</div>;
    };
    
    export default Example;

    A plugin is usually a function that receives optional plugin parameters and returns an object containing the plugin name and other config.

    In the example above, we define a plugin named plugin-example. It defines a global environment variable, process.env.SLUG, during the build phase and injects the global component Example.tsx into the page.

    2. Use a plugin

    Register plugins via plugins in rspress.config.ts:

    rspress.config.ts
    import { pluginExample } from './plugin';
    
    export default {
      plugins: [pluginExample('test')],
    };

    The Example component is then injected into the page, and the component can access process.env.SLUG.