在我正在开发的单页应用程序中,我使用的是Vite,在我的vite.config.ts文件中,我有以下代理:
proxy: {
'/v1': {
target: 'https://127.0.0.1:8080',
changeOrigin: true,
secure: false
}
}是否有一种方法来改变这个目标取决于它是否在生产环境?类似于:
proxy: {
'/v1': {
target: isDev ? 'https://127.0.0.1:8080' : 'https://api.example.com',
changeOrigin: isDev,
secure: !isDev
}
}也就是说,在我的本地环境中,我想要针对本地服务器进行开发,这样,像fetch("/v1/get-posts")这样的获取API调用就会被转发到https://127.0.0.1:8080/v1/get-posts,但是在我的产品构建(我通过vite build创建)中,它们将被转发到:https://api.example.com/v1/get-posts。
可以这样做吗?如果可以,怎么做?
发布于 2022-03-19 23:24:49
dev服务器及其代理配置没有绑定到构建输出中,因此您的目标在实际中没有多大意义。但是,从技术上讲,您可以通过mode标志在生产模式下运行dev服务器,所以这也许就是您的意思。
在这种情况下,您可以使用条件配置,其中isDev将是mode === 'development'
// vite.config.js
import { defineConfig } from 'vite'
import { fileURLToPath } from 'url'
import vue from '@vitejs/plugin-vue'
const defaultConfig = {
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
}
export default defineConfig(({ command, mode }) => {
if (command === 'serve') {
const isDev = mode === 'development'
return {
...defaultConfig,
server: {
proxy: {
'/v1': {
target: isDev ? 'https://127.0.0.1:8080' : 'https://api.example.com',
changeOrigin: isDev,
secure: !isDev
}
}
}
}
} else {
return defaultConfig
}
})https://stackoverflow.com/questions/71534594
复制相似问题