创建一个文件
let fs = require('fs')
//返回package的json数据
const getPackageJson = () => {
let data = fs.readFileSync('./package.json') //fs读取文件
return JSON.parse(data) //转换为json对象
}
let packageData = getPackageJson()
const getCurrentDate = () => {
let time = new Date()
let a = time.toLocaleDateString()
let x = a.split('/')
if (x[1].length < 2) {
x[1] = '0' + x[1]
}
if (x[2].length < 2) {
x[2] = '0' + x[2]
}
return x.join('')
}
const changeVersion = () => {
if (getCurrentDate() === String(packageData.version.split('.')[0])) {
let x = Number(packageData.version.split('.')[1])
x = x + 1
packageData.version = `${getCurrentDate()}.${x}`
} else {
packageData.version = `${getCurrentDate()}.1`
}
}
changeVersion()
fs.writeFile(
'./package.json',
JSON.stringify(packageData, null, '\t'),
(err) => {
if (err) {
console.log('写入失败', err)
} else {
console.log('版本号写入成功')
}
}
)
然后再修改package.json
"scripts": {
"dev": "vite --host",
"build": "node ./changeVersion.ts && vue-tsc --noEmit && vite build",
"preview": "vite preview"
},
最后在有版本号的地方,引用package.json,然后在页面上使用即可 packageConfig.version
import packageConfig from '../../../package.json'