在 package.json
中新增 "uni-app"
字段,定义不同环境的变量:
{
"name": "uni-preset-vue",
"version": "0.0.0",
"scripts": {
"dev": "uni -p staging", // 日常环境***复制后 注释删掉蛤
"prod": "uni -p production", // 生产环境***复制后 注释删掉蛤
...
},
"dependencies": {
...
},
"devDependencies": {
...
},
"uni-app": {
"scripts": {
"staging": {
"title": "日常环境",
"env": {
"UNI_PLATFORM": "mp-weixin"
},
"define": {
"ENV_STAGING": true
}
},
"production": {
"title": "生产环境",
"env": {
"UNI_PLATFORM": "mp-weixin"
},
"define": {
"ENV_PRODUCTION": true
}
}
}
}
}
// utils/http.js
/**
* 请求拦截处理
*/
const requestInterceptor = (config) => {
let envUrl = ''
// 添加基础路径
if (!config.url.startsWith('http')) {
// 注意这里的#ifdef ENV_STAGING ENV_STAGING必须与package.json中配置的
// "define": {
// "ENV_STAGING": true
// }保持一致
// ***AAA配置*** 使用条件编译配置不同环境的API地址
// #ifdef ENV_STAGING
envUrl = import.meta.env.VITE_API_BASE || 'https://dev-api.example.com'
// #endif
// #ifdef ENV_PRODUCTION
envUrl =
import.meta.env.VITE_API_BASE || 'https://api.example.com'
// #endif
config.url = envUrl + config.url
}
// 默认请求头
config.header = {
'Content-Type': 'application/json',
...config.header,
}
// 添加Token
// const token = uni.getStorageSync('token')
const token = 'bcac4a6d-91e5-4ee3-b448-ac92d2d85eab0'
if (token) {
// config.header.Authorization = `Bearer ${token}`
config.header['x-auth-token'] = token
}
// 显示加载状态
if (config.showLoading !== false) {
uni.showLoading({
title: config.loadingText || '加载中...',
mask: true,
})
}
return config
}
HBuilder X中运行-存在 生产环境和日常环境 两个环境选项: