在前端项目(Vue/React)打包时,将打包时间注入到项目中,可以有效防止前后端扯皮,尤其是在部署和调试时能够明确知道当前运行的代码版本和打包时间。以下是实现方案
在index.html中加入时间模板:
<div style="display: none">PUBLISHTIME</div>
安装一个文件管理依赖:
pnpm install fs-extra -D
然后新建一个script文件夹用于存储编译脚本,并存储编译脚本:
将里面的buildCmd替换为自己的命令
const fs = require('fs-extra')
const path = require('path')
const { exec } = require('child_process')const buildCmd = 'pnpm run test'const updateDeployTime = () => {const indexHtml = path.join(__dirname, '../index.html')let content = fs.readFileSync(indexHtml, 'utf-8')if (content.includes(`PUBLISHTIME`)) {var currentTime = new Date()// 提取年、月、日、时、分、秒var year = currentTime.getFullYear() // 年var month = String(currentTime.getMonth() + 1).padStart(2, '0')var day = String(currentTime.getDate()).padStart(2, '0') // 日var hours = String(currentTime.getHours()).padStart(2, '0') // 时var minutes = String(currentTime.getMinutes()).padStart(2, '0') // 分var seconds = String(currentTime.getSeconds()).padStart(2, '0') // 秒// 拼接成 YYYY-MM-DD HH:mm:ss 格式var formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`console.log('currentTime', formattedTime)content = content.replace('PUBLISHTIME', `build time: ${formattedTime}`)fs.writeFileSync(indexHtml, content)console.log(`Updated time in: ${indexHtml}`)}
}const deleteDistFolder = () => {const distFolder = path.join(__dirname, '../dist')if (fs.existsSync(distFolder)) {fs.remove(distFolder)console.log(`Deleted folder: ${distFolder}`)} else {console.log(`Folder does not exist: ${distFolder}`)}
}const testBuild = () => {// Step 1: Run the build commandconsole.log('Starting build process...')exec(buildCmd + ' && git restore .', (error, stdout, stderr) => {if (error) {console.error(`Build error: ${error.message}`)return}if (stderr) {console.error(`Build stderr: ${stderr}`)}console.log(`Build stdout: ${stdout}`)console.log('Build process complete.')})
}// 从命令行获取新服务的名称
exec('git add .', (error, stdout, stderr) => {// del dist folderdeleteDistFolder()// update build timeupdateDeployTime()// run build test commandtestBuild()// upload dist folder to server
})
然后在package.json里面添加编译命令:
"pub:test": "node scripts/test.cjs",
"pub:prod": "node scripts/prod.cjs"