微信小程序环境变量配置方法

最近在做微信小程序项目遇到一个问题,怎么区分本地、体验版、生产环境,通过环境变量设置来做区分配置不同环境下不同的API地址,最后用到wx.getAccountInfoSync()方法:

实例

根目录新建congfig.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 判断环境变量 develop: 开发版,trial:体验版,release:正式版
const envObj = wx.getAccountInfoSync()
const { envVersion, appId } = envObj.miniProgram
const config = {
develop: {
wx_tp_webview: 'http://192.168.2.115:8080',
apiBase: 'https://api.test.com'
},
trial: {
wx_tp_webview: 'https://test.xxxx.com',
apiBase: 'https://api.test.com'
},
release: {
wx_tp_webview: 'https://www.xxxx.com',
apiBase: 'https://api.prod.com'
},
}
module.exports = config[envVersion]

公共变量调用app.js

1
2
3
4
5
6
import config from './config'
App({
onLaunch: function (options) {},
wx_tp_webview : config.wx_tp_webview,
...
})

公共接口配置调用api.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import config from './config'
const ApiBaseUrl = config.apiBase

wx.request({
url: ApiBaseUrl + url,
method,
header,
data,
dataType: 'json',
success: function (res) {
console.log(res,'----res')
},
fail: function (res) {
console.log(res,'----res')
},
});

...

再也不用每次发体验版改一次地址,本地调试改一次,发生产再改一次地址了哈。。。。