需求背景:

基于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配置如何配置化修改
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐