dev.setupMiddlewares

    • Type:
    type SetupMiddlewaresServer = {
      sockWrite: (
        type: string,
        data?: string | boolean | Record<string, any>,
      ) => void;
      environments: EnvironmentAPI;
    };
    
    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 through the environment API.
    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();
            });
          },
        ],
      },
    };