业务场景: 执行 npm run build 打包部署的时候自动生成版本号,方便部署后客户端提示更新。
1. 创建读取写入流文件
// 创建changeVersion.ts
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 = () => {
// getCurrentDate().substring(0, 6) == 202305 ;
// 月份不相同时,直接更改。
if (getCurrentDate().substring(0, 6) === String(packageData.version.split('.')[0])) {
let x = Number(packageData.version.split('.')[2])
x = x + 1
let d = getCurrentDate().substring(0, 6) + '.' + getCurrentDate().substring(6);
packageData.version = `${d}.${x}`
} else {
let d = getCurrentDate().substring(0, 6) + '.' + getCurrentDate().substring(6);
packageData.version = `${d}.1`
}
}
changeVersion()
fs.writeFile(
'./package.json',
JSON.stringify(packageData, null, '\t'),
(err) => {
if (err) {
console.log('写入失败', err)
} else {
console.log('版本号写入成功',packageData.version)
// packageData.version ---> 202305.11.7
}
}
)
2. 更改package.json文件
- 更改build中的执行命令 node ./version/changeVersion.ts && node build/build.js
"name": "cmsv9",
"version": "202305.11.7",
"description": "cmsv9-cli",
"author": "hq",
"private": true,
"scripts": {
"dev": "webpack-dev-server --inline --progress --public --config build/webpack.dev.conf.js",
"start": "npm run dev",
"install": "cnpm install",
// This!!!!!!
"build": "node ./version/changeVersion.ts && node build/build.js",
"analyz": "NODE_ENV=production npm_config_report=true npm run deploy:prod"
},
3. 在version.js中使用版本号(在哪使用在哪引入)
import packageVersion from '../package.json'
const version = packageVersion.version;
export default { version }
4. 在App.vue中引入版本号,并处理缓存
import _v from '../version/version.js'
created() {
this.checkForUpdate()
},
methods: {
//检查版本更新
checkForUpdate() {
let currentVersion = _v.version;
if(currentVersion !== localStorage.getItem("version")){
this.loading = true;
this.$alert('检测到新版本,请刷新网页以加载新版本','更新提示', {
confirmButtonText: '确定',
showClose: false,
callback: () => {
// 更新本地缓存的版本
window.sessionStorage.clear();
window.localStorage.clear();
window.location.reload(true);
localStorage.setItem("version", currentVersion);
this.loading = true;
}
})
}
}
}