我曾经写过一篇文章,《解决vue前端发版后要刷新才能看到更新的问题》,每次发版时,都需要手动更改版本号,这让我感到有些不便。因此,我开始思考是否有办法在每次打包时自动增加版本号。为了解决这个问题,我开始进行了一些研究。
首先,需要在根文件目录下添加updateVersion.js文件:
const fs = require('fs')
// 读取 version.json 文件 例如:1.0.0
const versionJsonPath = './public/version.json'
const versionJson = JSON.parse(fs.readFileSync(versionJsonPath, 'utf8'))
// 自动递增版本号
const currentVersion = versionJson.version
const newVersion = incrementalVersion(currentVersion)
// 修改 version 字段
versionJson.version = newVersion
// 将修改后的内容写入 version.json 文件
fs.writeFileSync(versionJsonPath, JSON.stringify(versionJson, null, 2), 'utf8')
console.log(`版本号已更新为: ${newVersion}`)
// 递增版本号
function incrementalVersion (version) {
const versionParts = version.split('.')
let major = parseInt(versionParts[0])
let minor = parseInt(versionParts[1])
let patch = parseInt(versionParts[2])
if (patch < 99) { // 最后一位数若大于99,patch变为0,则前一位(minor)➕1,
patch += 1
} else {
patch = 0
minor += 1
}
if (minor > 99) { // 同 patch一样
major += 1
minor = 0
}
return `${major}.${minor}.${patch}`
}
后面我们需要在打包时去执行版本号递增,需在package.json文件中打包时加上node update-version.js
{
"scripts": {
"build": "vue-cli-service build --mode uat",
"build:uat": "node update-version.js && vue-cli-service build --mode uat",
"build:prod": "node update-version.js && vue-cli-service build --mode production",
}
}