当前位置:   article > 正文

uni-app构建改写manifest.json配置_uniapp manifest.json配置后端服务器

uniapp 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/"
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
如何做到可配置化改写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('
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/710339
推荐阅读
相关标签