直接上干货
vite.config.ts
:
import { defineConfig, loadEnv } from 'vite'
// https://vitejs.dev/config/
export default ({ mode }) =>
defineConfig({
server: { // 开发服务器配置
port: 3333, // 开发服务器端口
proxy: {
[loadEnv(mode, process.cwd()).VITE_APP_BASE_API]: {
target: loadEnv(mode, process.cwd()).VITE_APP_REAL_API, // 腾讯云服务器
// target: 'http://localhost:3003', // animal_server
changeOrigin: true,
rewrite: path => {
const apiString = loadEnv(mode, process.cwd()).VITE_APP_BASE_API
const envApi = new RegExp(apiString, 'g')
return path.replace(envApi, '')
},
},
},
},
})
还可以:
const config = loadEnv('development', './')
export default defineConfig({
server: {
proxy: {
config.VITE_APP_BASE_API: config.VITE_APP_REAL_API,
// '/api': config.VITE_APP_REAL_API
},
},
})
.env.development
文件:
# just a flag
ENV = 'development'
# base api 个人习惯给代理别名也明确环境
VITE_APP_BASE_API = '/dev-api'
# real api
VITE_APP_REAL_API = 'http://localhost:3003'
# VITE_APP_REAL_API = 'http://xxx.xx.xxx.xxx:3003'