uni-app构建改写manifest.json配置

需求背景:

基于uni-app的移动端项目,test环境,uat环境,prod环境需要部署到域名根目录下不同目录。如果每次部署投产前都依靠分支手动修改路径,存在风险,易造成生产事故。

配置如下:
manifest.json文件中的router配置

{
    "name" : "IAMS",
    "appid" : "",
    "description" : "",
    "versionName" : "1.0.0",
    "versionCode" : "100",
    "transformPx" : false,
    
    "h5" : {
        "router" : {
            "base" : "/test-app/"
        }
    }
}
如何做到可配置化改写router
  • 构建测试环境,路径为test-app
  • 构建测试uat,路径为uat-app
  • 构建生产环境,路径为prd-app

思路

执行构建命令时,改写manifest配置

开始

根目录新建vue.config.js文件

  1. 引入配置文件
  2. 根据环境变量,配置路径
  3. 打包构建时会动态写入对应配置

代码

const fs = require('fs')
const manifestPath = './src/manifest.json'

//1.--------------重写配置文件------------------
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')
}

//2.配置打包路由
const publicPathMap = {
    "development:h5": "/test-app/",
    "uat:h5": "/uat-app/",
    "production:h5": "/prd-app/"
}
//3.根据构建写入对应配置
replaceManifest("router.base", JSON.stringify(publicPathMap[process.env.NODE_ENV]))
// console.log('🚀--Manifest-->>>', Manifest)
fs.writeFileSync(manifestPath, Manifest, {
    "flag": "w"
})

根据此配置,无需要考虑每个分支不同配置代码冲突问题,也不需要每次部署前手动修改,通过运行对应的打包命令部署构建即可。

水平展开

微信小程序多appid部署的appid配置如何配置化修改
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值