第三十二章-Vite配置-server.proxy

1.说明

原文:

类型: Record<string, string | ProxyOptions>

为开发服务器配置自定义代理规则。期望接收一个 { key: options } 对象。如果 key 值以 ^ 开头,将会被解释为 RegExp

使用 http-proxy。完整选项详见 此处.

示例:

export default {
  server: {
    proxy: {
      // 字符串简写写法
      '/foo': 'http://localhost:4567/foo',
      // 选项写法
      '/api': {
        target: 'http://jsonplaceholder.typicode.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      },
      // 正则表达式写法
      '^/fallback/.*': {
        target: 'http://jsonplaceholder.typicode.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/fallback/, '')
      }
    }
  }
}

参考连接:

2.VbenAdmin代码解析

我们在build文件夹下创建一个vite文件,这么放置所有和vite配置有关的文件。然后完成本章两个文件的编写。

2.1.proxy.ts

build\vite\proxy.ts,注意,这里带注解的代码和原代码不一样。因为原代码我感觉有点问题。

Vite官方文档说代理配置接收的是一个Record<string, string | ProxyOptions>对象。而这个文件的主要方法返回的是ProxyTargetList类型的对象。

按理来说ProxyTargetList应该直接等于Record<string, string | ProxyOptions>

但是VbenAmin的代码安装了一个@types/http-proxy(虽然Vite本身的代理就是用http-proxy实现的)的开发依赖。然后从这个开发依赖里面导入一个ServerOptions。让ProxyTargetList等于Record<string, ServerOptions & { rewrite: (path: string) => string }>

个人感觉可以直接使用vite提供的类型即可,不用安装@types/http-proxy的声明文件。

2.1.1.带注解的代码

被代理之后,访问的路径是 代理至的路径 + 访问的路径去掉根路径后经过rewrite处理的路径。

/**
 * .env.development 的 代理配置
 */
import type { ProxyOptions } from 'vite';

// ↓第一项被代理的路径,第二项代理至的路径
type ProxyItem = [string, string];

// ↓方法接收的参数
type ProxyList = ProxyItem[];

// ↓Vite代理所接收对象类型
type ProxyTargetList = Record<string, string | ProxyOptions>;

// ↓https类型的URL的匹配正则
const httpsRE = /^https:\/\//;

/**
 * 生成Vite代理配置的方法
 */
export function createProxy(list: ProxyList = []) {
  const ret: ProxyTargetList = {};
  for (const [prefix, target] of list) {
    const isHttps = httpsRE.test(target);

    // https://github.com/http-party/node-http-proxy#options
    ret[prefix] = {
      // ↓代理至的路径
      target: target,
      // ↓默认值:false-将主机标头的来源更改为目标URL
      changeOrigin: true,
      // ↓如果您想代理websocket
      ws: true,
      rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ''),
      // https is require secure=false
      ...(isHttps ? { secure: false } : {}),
    };
  }
  return ret;
}

2.1.2.原代码

/**
 * Used to parse the .env.development proxy configuration
 */
import type { ServerOptions } from 'http-proxy';

type ProxyItem = [string, string];

type ProxyList = ProxyItem[];

type ProxyTargetList = Record<string, ServerOptions & { rewrite: (path: string) => string }>;

const httpsRE = /^https:\/\//;

/**
 * Generate proxy
 * @param list
 */
export function createProxy(list: ProxyList = []) {
  const ret: ProxyTargetList = {};
  for (const [prefix, target] of list) {
    const isHttps = httpsRE.test(target);

    // https://github.com/http-party/node-http-proxy#options
    ret[prefix] = {
      target: target,
      changeOrigin: true,
      ws: true,
      rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ''),
      // https is require secure=false
      ...(isHttps ? { secure: false } : {}),
    };
  }
  return ret;
}

2.2.vite.config.ts

直接将上面定义的生成代理配置的方法放到vite.config.ts中使用。

// ...

import { createProxy } from './build/vite/proxy';

// ...

export default ({ command, mode }: ConfigEnv): UserConfig => {
  // ...
  return {
    // ...
    server: {
   	  // ...
      // 从.env加载代理配置
      proxy: createProxy(VITE_PROXY),
    },
    // ...
  };
};

上一章

第三十一章-Vite配置-server.port

下一章

第三十三章-Vite配置-server.hmr

# vben  vite 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×