Uniapp 环境变量设置记录
官方文档:https://uniapp.dcloud.io/collocation/vue-config
官方文档只是说明了最核心的配置方式,但稍微注意一下,因为官方文档默认,用户是Node
高手,所以不会告知以下几个坑。
-
在项目文件夹内安装,对应的插件。如:
webpack
,copy-webpack-plugin
。这两个依赖项,用于修改环境变量,与拷贝复制。请按需安装。
-
传入参数时,要严格按照类型来传入,自定义环境变量,如果这个变量是
string
类型比如:官方内置,修改
manifest.json
时,实例replaceManifest
函数中,"xxxx"
字符串,需要用'"xxx"'
,单引号包裹,才能传入正确类型.
片段
本片段,是通过外部导入自定义配置文件,只要传入对应的配置序号,就能替换覆盖环境变量,与wxAppID,自己编译
const webpack = require('webpack') // 记得安装 npm install webpack
const fs = require('fs')
const path = require('path')
// 对应 wx_client_list.json 客户端序号
const CLIENT_index = 0;
// 同步获取 json 文件,字符串
let wx_client_list = fs.readFileSync(path.join(__dirname,'wx_client_list.json'),{ encoding: 'utf-8' })
wx_client_list = JSON.parse(wx_client_list);// 序列化成对象
// 读取 manifest.json ,修改后重新写入
const manifestPath = path.join(__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')
}
// 使用
replaceManifest('mp-weixin.appid', '"'+wx_client_list.data[CLIENT_index].key+'"')
// 同步写入文件
fs.writeFileSync(manifestPath, Manifest, {
"flag": "w"
})
module.exports = {
chainWebpack: config => {
config
.plugin('define')
.tap(args => {
// 设置 内部 env 环境变量
args[0]['process.env'].CLIENT_ID = wx_client_config.data[CLIENT_index].id // 数字类型
args[0]['process.env'].SERVER_DEVELOPMENT = '"'+wx_client_config.server_config.development+'"' // 字符串类型
args[0]['process.env'].SERVER_PRODUCTION = '"'+wx_client_config.server_config.production+'"' // 字符串类型
return args
})
}
}