1.在package.json文件中,增加uni-app节点:
image.png
"uni-app": {
"scripts": {
"dev": {
"title": "微信小程序—开发环境",
"env": {
"VUE_APP_ENV_TYPE": "dev",
"UNI_PLATFORM": "mp-weixin"
},
"define": {
"MP-WEIXIN": true
}
},
"test": {
"title": "微信小程序—测试环境",
"env": {
"VUE_APP_ENV_TYPE": "test",
"UNI_PLATFORM": "mp-weixin"
},
"define": {
"MP-WEIXIN": true
}
},
"stage": {
"title": "微信小程序—stage环境",
"env": {
"VUE_APP_ENV_TYPE": "stage",
"UNI_PLATFORM": "mp-weixin"
},
"define": {
"MP-WEIXIN": true
}
},
"production": {
"title": "微信小程序—生产环境",
"env": {
"VUE_APP_ENV_TYPE": "production",
"UNI_PLATFORM": "mp-weixin"
},
"define": {
"MP-WEIXIN": true
}
}
}
}
2.根目录新建config文件夹
image.png
image.png
// 开发环境
const dev = {
baseUrl: 'https://dev.....',
appid: 'wxf0701ab381cd8144'
}
// 测试环境
const test = {
baseUrl: 'https://test.....',
appid: 'wxf0701ab381cd8144'
}
// staging环境
const stage = {
baseUrl: 'https://test.....',
appid: 'wxf0701ab381cd8144'
}
// 生产环境
const production = {
baseUrl: 'https://production.....',
appid: 'wxf0701ab381cd8144'
}
// 注意:这里的属性名要和上面package.json中定义的扩展节点编译名称相同
const ENV_CONFIG = {
dev,
test,
stage,
production,
}
module.exports = ENV_CONFIG
- 根目录新建vue.config.js
// 导入fs模块
const fs = require('fs')
// 导入环境变量配置文件
const ENV_CONFIG = require('./config/env.js')
const manifestPath = `${__dirname}/manifest.json`;
let Manifest = fs.readFileSync(manifestPath, {
encoding: 'utf-8'
})
function replaceManifest(path, value) {
const arr = path.split('.')
const len = arr.length
const lastItem = arr[len - 1]
let i = 0
let ManifestArr = Manifest.split(/\n/)
for (let index = 0; index < ManifestArr.length; index++) {
const item = ManifestArr[index]
if (new RegExp(`"${arr[i]}"`).test(item)) ++i
if (i === len) {
const hasComma = /,/.test(item)
ManifestArr[index] = item.replace(
new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`),
`"${lastItem}": ${value}${hasComma ? ',' : ''}`
)
break
}
}
Manifest = ManifestArr.join('\n')
}
// 读取环境变量内容
const appid = ENV_CONFIG[process.env.UNI_SCRIPT].appid
if (appid) {
replaceManifest('mp-weixin.appid', `"${appid}"`)
}
fs.writeFileSync(manifestPath, Manifest, {
flag: 'w'
})
4.使用:
import ENV_CONFIG from "./config/env.js";
console.log(ENV_CONFIG[process.env.VUE_APP_ENV_TYPE].baseUrl);
image.png
image.png
或者将ENV_CONFIG挂载到全局:
import Vue from "vue";
import App from "./App";
Vue.config.productionTip = false;
// //禁止某些页面分享
// let share = require("../utils/share");
// Vue.mixin(share);
import uView from "uview-ui";
Vue.use(uView);
import store from "./store/index.js";
import ENV_CONFIG from "./config/env.js";
Vue.prototype.$store = store;
Vue.prototype.$env = ENV_CONFIG;
App.mpType = "app";
const app = new Vue({
store,
...App,
});
app.$mount();
image.png