From f39a2aafd35a70effc298d53b0b7539fbac79e89 Mon Sep 17 00:00:00 2001 From: Timo Zander Date: Wed, 13 Jan 2021 17:15:20 +0100 Subject: [PATCH] feat(vite): support RegExp strings as server.proxy keys (#1510) --- docs/config/index.md | 10 +++++++++- packages/vite/src/node/server/middlewares/proxy.ts | 5 ++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/docs/config/index.md b/docs/config/index.md index 9ed1d9d6de9136..2ae7362aa705fb 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -239,7 +239,9 @@ export default ({ command, mode }) => { - **Type:** `Record` - Configure custom proxy rules for the dev server. Expects an object of `{ key: options }` pairs. Uses [`http-proxy`](https://github.com/http-party/node-http-proxy). Full options [here](https://github.com/http-party/node-http-proxy#options). + Configure custom proxy rules for the dev server. Expects an object of `{ key: options }` pairs. If the key starts with `^`, it will be interpreted as a `RegExp`. + + Uses [`http-proxy`](https://github.com/http-party/node-http-proxy). Full options [here](https://github.com/http-party/node-http-proxy#options). **Example:** @@ -255,6 +257,12 @@ export default ({ command, mode }) => { changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') } + // with RegEx + '^/fallback/.*': { + target: 'http://jsonplaceholder.typicode.com', + changeOrigin: true, + rewrite: (path) => path.replace(/^\/fallback/, '') + } } } } diff --git a/packages/vite/src/node/server/middlewares/proxy.ts b/packages/vite/src/node/server/middlewares/proxy.ts index 51dbb956b5e7fd..59750b35f84eed 100644 --- a/packages/vite/src/node/server/middlewares/proxy.ts +++ b/packages/vite/src/node/server/middlewares/proxy.ts @@ -78,7 +78,10 @@ export function proxyMiddleware({ return (req, res, next) => { const url = req.url! for (const context in proxies) { - if (url.startsWith(context)) { + if ( + (context.startsWith('^') && new RegExp(context).test(url)) || + url.startsWith(context) + ) { const [proxy, opts] = proxies[context] if (opts.bypass) {