1.新建sysInfo.json文件
perl
{
"version": "20240307@1.0.1"
}
2.新建addVersion.js文件,打包时执行,将版本号写入sysInfo.json文件
ini
//npm run build打包前执行此段代码
let fs = require('fs')
//返回package的json数据
function getPackageJson() {
let data = fs.readFileSync('./src/assets/json/sysInfo.json') //fs读取文件
return JSON.parse(data) //转换为json对象
}
let packageData = getPackageJson() //获取package的json
let arr = packageData.version.split('@') //切割后的版本号数组
let date = new Date()
const year = date.getFullYear()
let month = date.getMonth() + 1
let day = date.getDate()
month = month > 9 ? month : '0' + month
day = day < 10 ? '0' + day : day
let today = `${year}${month}${day}`
let verarr = arr[1].split('.')
verarr[2] = parseInt(verarr[2]) + 1
packageData.version = today + '@' + verarr.join('.') //转换为以"."分割的字符串
//用packageData覆盖package.json内容
fs.writeFile('./src/assets/json/sysInfo.json', JSON.stringify(packageData, null, '\t'), err => {
console.log(err)
})
3.package.json中配置
json
"scripts": {
"dev": "vite",
"serve": "vite",
"build": "node ./src/addVersion.js && vite build",
....
4.使用
javascript
import sysInfo from '@/assets/json/sysInfo.json'