前后端分离开发模式中,无论前后端都有可能区分不同的环境配置,开发环境(dev)、测试环境(test)、线上生产环境(prod)等,不同环境的设置,后端请求api地址等不同,那么在小程序如何设置多环境配置呢?
定义其他的环境变量
之前搞vue的时候 可以通过 .env的方式配置开发测试和线上需要的环境变量
uniapp中只有 development 和 production 这两个条件
vu2版本通过process.env.NODE_ENV可以获取到
我如果需要其他的变量怎么办呢: 如 测试 test等
通过官网我们可以看到示例
在根目录下的 package.json文件中 (没有的话通过 npm init -y初始化创建一个)
{"uni-app": {"scripts": {"dev": {"title": "微信小程序——开发版","env": {"ENV_TYPE": "dev","UNI_PLATFORM": "mp-weixin","VUE_APP_BASE_URL": "http://127.0.0.1:8080/"}},"test": {"title": "微信小程序——测试版","env": {"ENV_TYPE": "test","UNI_PLATFORM": "mp-weixin","VUE_APP_BASE_URL": "http://test.domain/"}},"pro": {"title": "微信小程序——正式版","env": {"ENV_TYPE": "pro","UNI_PLATFORM": "mp-weixin","VUE_APP_BASE_URL": "http://pro.domain/"}}}},"name": "xm-uni-app","version": "1.0.0","description": "{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**}","main": "main.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"repository": {"type": "git","url": ""},"keywords": [],"author": "","license": "ISC"}
保存之后,在HBuilderX中会显示在 运行/发行 菜单中
vue2版本中使用
直接通过process.env打印的时候会看不到
直接通过process.env.变量名使用就行
console.log(process.env.VUE_APP_BASE_URL,'获取处于当前开发环境的url');console.log(process.env.ENV_TYPE,'获取当前处于哪个开发环境');console.log(process.env,'process.env++++++++++++');
vue3 vite版中使用
在vue3中获取不到process,所以需要一些改造
{"uni-app": {"scripts": {"dev": {"title": "微信小程序——开发版","env": {"ENV_TYPE": "dev","UNI_PLATFORM": "mp-weixin","VITE_BASE_API": "http://127.0.0.1:8080/"}},"test": {"title": "微信小程序——测试版","env": {"ENV_TYPE": "test","UNI_PLATFORM": "mp-weixin","VITE_BASE_API": "http://test.domain/"}},"pro": {"title": "微信小程序——正式版","env": {"ENV_TYPE": "pro","UNI_PLATFORM": "mp-weixin","VITE_BASE_API": "http://pro.domain/"}}}}}
在src/utils文件夹下创建envConfig.js
// 导出的环境请求地址//本地环境const dev = {ENV: "dev",VITE_BASE_API: "http://127.0.0.1:8080/dev-api",};//正式环境const pro = {ENV: "pro",VITE_BASE_API: "https://xxx/prod-api",};//测试环境const test = {ENV: "test",VITE_BASE_API: "https://xxx/test-api",};export default {dev,test,pro,};
在vite.config.js添加配置
import { defineConfig } from "vite";import uni from "@dcloudio/vite-plugin-uni";import ENV_CONFIG from "./utils/envConfig.js";import { resolve } from "path"; // 导入 path 模块,帮助我们解析路径export default defineConfig(() => {return {server: {port: "3002",},resolve: {alias: {"@": resolve(__dirname, "/src"),},},plugins: [uni()],define: {"process.env.config": ENV_CONFIG, //配置一'process.env': process.env, //配置二},};});
使用方式
let baseURL = process.env.config[process.env.UNI_SCRIPT].VITE_BASE_API; //获取处于当前开发环境的urllet evnName = process.env.config[process.env.UNI_SCRIPT].ENV; //获取当前处于哪个开发环境console.log("baseURL:", baseURL, "++++++++++++++++++++++++");console.log("envName:", evnName, "++++++++++++++++++++++++");console.log("evn:", process.env, "++++++++++++++++++++++++");