dev.setupMiddlewares

    • Type:
    type SetupMiddlewaresServer = {
      sockWrite: (
        type: string,
        data?: string | boolean | Record<string, any>,
      ) => void;
      environments: {
        [name: string]: {
          /**
           * Get stats info about current environment.
           */
          getStats: () => Promise<Stats>;
          /**
           * Load and execute stats bundle in server.
           *
           * @param entryName - relate to Rsbuild's `source.entry`
           * @returns the return value of entry module.
           */
          loadBundle: <T = unknown>(entryName: string) => Promise<T>;
    
          /**
           * Get the compiled HTML template.
           */
          getTransformedHtml: (entryName: string) => Promise<string>;
        };
      };
    };
    
    type SetupMiddlewares = Array<
      (
        middlewares: {
          unshift: (...handlers: RequestHandler[]) => void;
          push: (...handlers: RequestHandler[]) => void;
        },
        server: SetupMiddlewaresServer,
      ) => void
    >;
    • Default: undefined

    Provides the ability to execute a custom function and apply custom middlewares.

    The order among several different types of middleware is: unshift => internal middlewares => push.

    export default {
      dev: {
        setupMiddlewares: [
          (middlewares, server) => {
            middlewares.unshift((req, res, next) => {
              next();
            });
    
            middlewares.push((req, res, next) => {
              next();
            });
          },
        ],
      },
    };

    It is possible to use some server api to meet special scenario requirements:

    • sockWrite. Allow send some message to HMR client, and then the HMR client will take different actions depending on the message type. If you send a "content changed" message, the page will reload.
    export default {
      dev: {
        setupMiddlewares: [
          (middlewares, server) => {
            // add custom watch & trigger page reload when change
            watcher.on('change', (changed) => {
              server.sockWrite('content-changed');
            });
          },
        ],
      },
    };
    • environments. Allow operations in the specified environment.
    export default {
      dev: {
        setupMiddlewares: [
          (middlewares, server) => {
            middlewares.unshift(async (req, _res, next) => {
              const webStats = await server.environments.web.getStats();
    
              console.log(webStats.toJson({ all: false }));
    
              next();
            });
          },
        ],
      },
    };