server.proxy
type ProxyConfig =
  | Record<string, string | ProxyOptions>
  | ProxyOptions[]
  | ProxyOptions;
 
为开发服务器或预览服务器配置代理规则,将请求代理到指定的服务上。
示例
基础用法
rsbuild.config.ts
export default {
  server: {
    proxy: {
      // http://localhost:3000/api -> http://localhost:3000/api
      // http://localhost:3000/api/foo -> http://localhost:3000/api/foo
      '/api': 'http://localhost:3000',
    },
  },
};
 
此时,/api/users 请求将会代理到 http://localhost:3000/api/users。
你也可以代理到线上域名,比如:
rsbuild.config.ts
export default {
  server: {
    proxy: {
      // http://localhost:3000/api -> https://nodejs.org/api
      // http://localhost:3000/api/foo -> https://nodejs.org/api/foo
      '/api': 'https://nodejs.org',
    },
  },
};
 
重写路径
如果你不想传递 /api,可以通过 pathRewrite 重写请求路径:
rsbuild.config.ts
export default {
  server: {
    proxy: {
      // http://localhost:3000/api -> http://localhost:3000
      // http://localhost:3000/api/foo -> http://localhost:3000/foo
      '/api': {
        target: 'http://localhost:3000',
        pathRewrite: { '^/api': '' },
      },
    },
  },
};
 
代理 WebSocket 请求
如果你希望代理 WebSocket 请求,可以通过 ws 开启:
rsbuild.config.ts
export default {
  server: {
    proxy: {
      '/rsbuild-hmr': {
        target: 'http://localhost:3000', // 将会代理到 ws://localhost:3000/rsbuild-hmr
        ws: true,
      },
    },
  },
};
 
选项
Rsbuild server proxy 基于 http-proxy-middleware 实现。你可以使用 http-proxy-middleware 的所有配置项,具体可以查看文档。
Rsbuild server proxy 完整类型定义为:
import type { Options as HttpProxyOptions } from 'http-proxy-middleware';
type Filter = string | string[] | ((pathname: string, req: Request) => boolean);
type ProxyOptions = HttpProxyOptions & {
  bypass?: (
    req: IncomingMessage,
    res: ServerResponse,
    proxyOptions: ProxyOptions,
  ) => MaybePromise<string | undefined | null | boolean>;
  context?: Filter;
};
type ProxyConfig =
  | ProxyOptions
  | ProxyOptions[]
  | Record<string, string>
  | Record<string, ProxyOptions>;
 
除了 http-proxy-middleware 的选项外,Rsbuild 还支持 bypass 和 context 两个选项。
bypass
一些情况下,你可能不想代理所有请求。可以通过 bypass 函数来绕过代理。
在函数中,你可以访问到 request、response 和 proxy 选项。
- 返回 
null 或 undefined 会继续用代理处理请求。 
- 返回 
true 会跳过代理继续处理请求。 
- 返回 
false 会返回 404 错误。 
- 返回一个具体的服务路径,将会使用此路径替代原请求路径。
 
- 返回一个 Promise,可以异步处理请求。
 
例如,你可能希望对浏览器请求返回 HTML 页面,而对 API 请求则进行代理转发。你可以这样配置:
rsbuild.config.ts
export default {
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        bypass(req, res, proxyOptions) {
          if (req.headers.accept.indexOf('html') !== -1) {
            console.log('Skipping proxy for browser request.');
            return '/index.html';
          }
        },
      },
    },
  },
};
 
context
用于代理多个指定的路径到同一个目标。
rsbuild.config.ts
export default {
  server: {
    proxy: [
      {
        context: ['/auth', '/api'],
        target: 'http://localhost:3000',
      },
    ],
  },
};