Rya*_*hel 6 http-proxy typescript devops vite
在我正在开发的单页应用程序中,我使用 Vite,在我的vite.config.ts文件中我有以下代理:
proxy: {
'/v1': {
target: 'https://127.0.0.1:8080',
changeOrigin: true,
secure: false
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法根据是否在生产环境中来改变这个目标?就像是:
proxy: {
'/v1': {
target: isDev ? 'https://127.0.0.1:8080' : 'https://api.example.com',
changeOrigin: isDev,
secure: !isDev
}
}
Run Code Online (Sandbox Code Playgroud)
也就是说,在我的本地环境中,我想针对本地服务器进行开发,这样我的 fetch API 调用就会fetch("/v1/get-posts")被转发到https://127.0.0.1:8080/v1/get-posts,但在我的生产构建(我通过vite build)中创建,它们将被转发到:https://api.example.com/v1/get-posts
这可以做到吗?如果可以,如何做到?
ton*_*y19 10
开发服务器及其代理配置没有捆绑到构建输出中,因此您的目标实际上没有多大意义。但是,从技术上讲,您可以通过该标志在生产模式下运行开发服务器mode,所以也许这就是您的意思。
在这种情况下,您可以使用条件配置,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
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10665 次 |
| 最近记录: |