You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vite构建的Node Web应用中配置不同环境的外部服务URL?

解决方案:在Vite配置或package.json中区分环境URL

当然可以,你有两种主要方式实现这个需求,不需要依赖未纳入版本控制的.env文件:

方法一:在vite.config.js中根据环境模式配置

Vite默认会区分development(本地开发,vite命令)和production(构建,vite build命令)两种模式,你可以直接在配置文件中根据当前模式指定对应URL,并注入到客户端代码中:

import { defineConfig } from 'vite'

export default defineConfig(({ mode }) => {
  // 根据模式选择服务器URL
  const serverUrl = mode === 'development' 
    ? 'http://localhost:3000/api' // 本地开发地址
    : 'https://prod-server.example.com/api'; // 生产构建地址

  return {
    define: {
      // 将URL注入为客户端可访问的全局变量,注意用JSON.stringify处理字符串
      '__SERVER_URL__': JSON.stringify(serverUrl)
    }
  }
})

之后在你的业务代码中,直接使用这个全局变量即可:

// 示例:发起请求
fetch(`${__SERVER_URL__}/user/list`)
  .then(res => res.json())
  .then(data => console.log(data))

方法二:通过package.json脚本传递环境变量

你也可以在package.json的脚本中直接指定不同环境的URL,再在Vite配置中读取这个变量:

  1. 修改package.json的scripts字段:
{
  "scripts": {
    "start": "SERVER_URL=http://localhost:3000/api vite",
    "build": "SERVER_URL=https://prod-server.example.com/api vite build"
  }
}

如果你需要跨Windows/Linux/macOS平台兼容,可以先安装cross-env包(npm install cross-env --save-dev),然后修改脚本为:

{
  "scripts": {
    "start": "cross-env SERVER_URL=http://localhost:3000/api vite",
    "build": "cross-env SERVER_URL=https://prod-server.example.com/api vite build"
  }
}
  1. 在vite.config.js中读取并注入这个变量:
import { defineConfig } from 'vite'

export default defineConfig({
  define: {
    '__SERVER_URL__': JSON.stringify(process.env.SERVER_URL)
  }
})

两种方法都能将URL配置纳入版本控制,推荐第一种方法——它更贴合Vite的原生环境模式机制,逻辑更清晰,无需额外依赖。

内容的提问来源于stack exchange,提问作者bosth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 22:02:22