import type { ProxyOptions } from 'vite'; /** * 处理运行环境配置项,使其拥有正确的类型 * * @template E * @param {(Record | E)} importMetaEnv 导入的环境变量 * @returns {E} */ export const resolveEnv = (importMetaEnv: Record | E): E => { const ret = {} as unknown as E; const envNameList = Object.keys(importMetaEnv) as (keyof E)[]; for (const envName of envNameList) { let value = typeof importMetaEnv[envName] === 'string' && importMetaEnv[envName].replace(/\\n/g, '\n'); value = value === 'true' ? true : value === 'false' ? false : value; if (typeof value === 'string' && value.startsWith('[') && value.endsWith(']')) { try { value = JSON.parse(value.replace(/'/g, '"')); } catch (error) { value = ''; } } ret[envName] = value; } return ret; }; /** * 开发服务器代理配置 * * @template L extends [string, ...string[]][] * @param {L} list 代理配置项 */ export const resolveProxy = (list: L) => { const httpsRE = /^https:\/\//; const ret: Record = {}; if (typeof list === 'object') { 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 需要开启 secure = false ...(isHttps ? { secure: false } : {}), }; } } return ret; };