Vue3 修改原有的多环境切换方式

Vue2 多环境配置:https://www.cnblogs.com/vipsoft/p/16696640.html

一般可以使用 Jenkins 对配置 .env.development.env.production,不同的环境进行构建
在没有 CI/CD 的情况下。Vue 项目的打包变得繁琐。
目前项目,使用一次打包,通过不同的 app-settings.ts 对项目环境进行切换。发版时,不同的环境只需保留 app-settings.ts 对其它文件进行替换即可

添加配置

app-settings.ts文件内容如下

// 1. 首先定义统一的配置接口
export interface EnvironmentSettings {
  environment: string;
  apiUrl: string;
  tocApiUrl: string;
}

export enum Environment {
  DEV = "dev",
  TEST = "test",
  PRE = "pre",
  PRO = "pro",
}

// 2. 使用常量对象而不是多个变量
const ENVIRONMENT_SETTINGS: Record<string, EnvironmentSettings> = {
  dev: {
    environment: "开",
    apiUrl: "https://xxxxx",
    tocApiUrl: "https://xxxxx",
  },
  test: {
    environment: "测",
    apiUrl: "https://xxxxx",
    tocApiUrl: "https://xxxxx",
  },
  pro: {
    environment: "",
    apiUrl: "https://xxxxx",
    tocApiUrl: "https://xxxxx",
  },
} as const;

// 3. 使用环境变量或构建时变量来决定使用哪个配置
type EnvironmentKey = keyof typeof ENVIRONMENT_SETTINGS;

// 可以通过环境变量、构建参数等方式动态选择环境
const getCurrentEnvironment = (): EnvironmentKey => {
  // 默认返回测试环境
  return Environment.PRE;
};

// 4. 导出选中的配置
const currentEnv = getCurrentEnvironment();
export default ENVIRONMENT_SETTINGS[currentEnv];

引用

global.d.ts


  /**
   * 系统设置
   */
  interface AppSettings {
    /** 系统标题 */
    title: string;  
    /** 系统环境 */
    environment: string;
    apiUrl: string;
    tocApiUrl: string;
  }

settings.ts

import envSettings from "./app-settings";

const defaultSettings: AppSettings = {
  // 系统Title
  title: `后台管理 (${envSettings.environment})`,
  // 环境
  environment: envSettings.environment,
  apiUrl: envSettings.apiUrl,
  tocApiUrl: envSettings.tocApiUrl,
}

export default defaultSettings;
import defaultSettings from "@/settings";

// 创建 axios 实例
const service = axios.create({
  //baseURL: import.meta.env.VITE_APP_BASE_API, 在 vite.config.js 中做代理
  baseURL: defaultSettings.apiUrl, //这边也可以设置特殊的值,在 vite.config.js 中做代理
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
  paramsSerializer: (params) => qs.stringify(params),
});

baseURL: import.meta.env.VITE_APP_BASE_API 改为 baseURL: defaultSettings.apiUrl

posted @ 2025-08-26 16:39  VipSoft  阅读(37)  评论(0)    收藏  举报