项目根目录添加<meta>标签,记录当前部署版本、分支、时间
一、背景
为了管理、追踪问题查阅方便,在根目录添加标签,记录当前部署项目的版本、分支、部署时间,项目环境(测试环境 or 线上环境);
二、步骤
1. 创建文件
- 在项目根目录下创建 scripts 文件夹(如果不存在);- 在scripts下创建 inject-meta.js 脚本文件;
2. 脚本核心功能实现
- 获取Git分支信息:使用 git rev-parse --abbrev-ref HEAD 命令;
- 获取当前时间:格式化为:YY - MM - dd HH - mm - ss;
- 生成meta标签:包含分支名和构建时间信息;
- HTML文件处理:读取、修改并写回html文件;
- 确定HTML文件路径: 根据实际情况获取正确的html文件路径;
const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')// 获取当前分支名
let branch = 'unknown'
try {branch = execSync('git rev-parse --abbrev-ref HEAD').toString().trim()
} catch (e) {}// 获取当前打包时间
const now = new Date()
const pad = n => n.toString().padStart(2, '0')
const buildTime = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`// 生成 meta 标签
const metaTag = `<meta name="branch-info" content="Branch: ${branch} | Build Time: ${buildTime}">`// 你的 index.html 路径(如有不同请修改)
const htmlPath = path.resolve(__dirname, '../dist/index.html')
let html = fs.readFileSync(htmlPath, 'utf-8')// 插入 meta 到 <head> 后面
if (!html.includes('name="branch-info"')) {html = html.replace(/<head>/, `<head>\n ${metaTag}`)fs.writeFileSync(htmlPath, html, 'utf-8')console.log('✅ branch-info meta tag injected!')
} else {console.log('ℹ️ branch-info meta tag already exists.')
}
3. 集成到构建流程
在package.json中配置:每个包名后增加:‘ && node scripts/inject-meta.js ’