赞
踩
声明此教程为HbuilderX官方工具创建的项目。
注:若没有package.json 请使用 npm init 进行初始化生成
此处也可以添加一些其他的环境变量
{
"uni-app" : {
"scripts": {
"prewx": {
"title": "测试版小程序",
"env": {
"UNI_PLATFORM": "mp-weixin",
"UNI_BASE_URL": "https://xxx.xxxx.com",
"UNI_BASE_APPID": "xxxx",
"UNI_BASE_NAME": "xxxxx"
}
},
"prodwx": {
"title": "正式版小程序",
"env": {
"UNI_PLATFORM": "mp-weixin",
"UNI_BASE_URL": "https://xxx.xxxx.com",
"UNI_BASE_APPID": "自定义appid,可以是不同的小程序id",
"UNI_BASE_NAME": "自定义appid,可以是不同的小程序id"
}
}
}
}
}
const fs = require('fs')
//process.env.UNI_INPUT_DIR为项目所在的绝对路径,经测试,相对路径会找不到文件
const manifestPath = process.env.UNI_INPUT_DIR + '/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')
}
//动态配置 appid和名称 ,这部分的代码可根据自己的需要写,需要改什么,按照manifest.json对应的路径写好即可
replaceManifest('mp-weixin.appid', `"${process.UNI_SCRIPT_ENV.UNI_BASE_APPID}"`)
replaceManifest('name', `"${process.UNI_SCRIPT_ENV.UNI_BASE_NAME}"`)
// console.log(process)
fs.writeFileSync(manifestPath, Manifest, {
"flag": "w"
})
1. config.js
// 当然也可以存一些别的环境变量,根据个人需要进行存储
module.exports = {
baseUrl: process.env.UNI_BASE_URL,
baseName: process.env.UNI_BASE_NAME,
baseAppId: process.env.UNI_BASE_APPID,
}
2. vue.config.js
let reWriteManifest = require('./modifyManifest')
在main.js中可以引入config.js直接挂载在Vue对象上
import config from './config.js'
Vue.prototype.$xxxx = config.xxxxx;
两处均可以运行哦,
打包的话同样会生成多个打包配置
这里我是添加了五套正式环境和测试环境的配置
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。