feat: add VITE_APP_PROXY 控制H5代理

This commit is contained in:
菲鸽 2024-05-18 17:24:21 +08:00
parent 4789b5ba41
commit b83541d483
5 changed files with 34 additions and 8 deletions

2
env/.env vendored
View File

@ -3,6 +3,8 @@ VITE_APP_PORT = 9000
# h5部署网站的base配置到 manifest.config.ts 里的 h5.router.base
VITE_APP_PUBLIC_BASE=/
# h5是否需要配置代理
VITE_APP_PROXY=true
VITE_UNI_APPID = 'H57F2ACE4'
VITE_WX_APPID = 'wxa2abb91f64032a2b'

2
src/env.d.ts vendored
View File

@ -15,6 +15,8 @@ interface ImportMetaEnv {
readonly VITE_SERVER_PORT: string
/** 后台接口地址 */
readonly VITE_SERVER_BASEURL: string
/** H5是否需要代理 */
readonly VITE_APP_PROXY: boolean
/** 上传图片地址 */
readonly VITE_UPLOAD_BASEURL: string
/** 是否清除console */

View File

@ -27,7 +27,18 @@ const httpInterceptor = {
}
// 非 http 开头需拼接地址
if (!options.url.startsWith('http')) {
// #ifdef H5
console.log(__VITE_APP_PROXY__)
if (JSON.parse(__VITE_APP_PROXY__)) {
// 啥都不需要做
} else {
options.url = baseUrl + options.url
}
// #endif
// 非H5正常拼接
// #ifndef H5
options.url = baseUrl + options.url
// #endif
// TIPS: 如果需要对接多个后端服务,也可以在这里处理,拼接成所需要的地址
}
// 1. 请求超时

View File

@ -12,3 +12,5 @@ declare const __UNI_PLATFORM__:
| 'quickapp-webview'
| 'quickapp-webview-huawei'
| 'quickapp-webview-union'
declare const __VITE_APP_PROXY__: 'true' | 'false'

View File

@ -35,7 +35,13 @@ export default ({ command, mode }) => {
console.log('UNI_PLATFORM -> ', UNI_PLATFORM) // 得到 mp-weixin, h5, app 等
const env = loadEnv(mode, path.resolve(process.cwd(), 'env'))
const { VITE_APP_PORT, VITE_SERVER_BASEURL, VITE_DELETE_CONSOLE, VITE_SHOW_SOURCEMAP } = env
const {
VITE_APP_PORT,
VITE_SERVER_BASEURL,
VITE_DELETE_CONSOLE,
VITE_SHOW_SOURCEMAP,
VITE_APP_PROXY,
} = env
console.log('环境变量 env -> ', env)
return defineConfig({
@ -87,6 +93,7 @@ export default ({ command, mode }) => {
],
define: {
__UNI_PLATFORM__: JSON.stringify(UNI_PLATFORM),
__VITE_APP_PROXY__: JSON.stringify(VITE_APP_PROXY),
},
css: {
postcss: {
@ -110,13 +117,15 @@ export default ({ command, mode }) => {
hmr: true,
port: Number.parseInt(VITE_APP_PORT, 10),
// 仅 H5 端生效其他端不生效其他端走build不走devServer)
// proxy: {
// '/api': {
// target: VITE_SERVER_BASEURL,
// changeOrigin: true,
// rewrite: (path) => path.replace(/^\/api/, ''),
// },
// },
proxy: JSON.parse(VITE_APP_PROXY)
? {
'/api': {
target: VITE_SERVER_BASEURL,
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
}
: undefined,
},
build: {
// 方便非h5端调试