如何将 Build at、Hash 和 Time git 的 Tag 号等构建信息,自动写入一个 JSON 文件

发布于:2025-05-09 ⋅ 阅读:(12) ⋅ 点赞:(0)

要将 Build atHashTime 等构建信息自动写入一个 JSON 文件(比如 build-info.json),你可以在 Vue CLI 项目中通过 Webpack 插件机制实现这个目标。

做法 ✅:


💡 步骤:使用 webpack 插件自定义输出构建信息

1. 在 vue.config.js 中添加以下配置:
const fs = require('fs')
const path = require('path')

module.exports = {
  configureWebpack: (config) => {
    config.plugins.push({
      apply: (compiler) => {
        compiler.hooks.done.tap('BuildInfoPlugin', (stats) => {
          const info = stats.toJson()

          const buildInfo = {
            buildAt: new Date().toISOString(),
            hash: info.hash,
            time: info.time, // 单位:ms
          }

          fs.writeFileSync(
            path.resolve(__dirname, 'dist/build-info.json'),
            JSON.stringify(buildInfo, null, 2),
            'utf-8'
          )

          console.log('\n✨ Build info written to dist/build-info.json')
        })
      }
    })
  }
}

🧪 构建后效果:

当你执行 npm run build 后,除了正常的构建产物外,dist/ 目录中还会多出一个文件:

// dist/build-info.json
{
  "buildAt": "2025-05-07T06:00:00.000Z",
  "hash": "a30cfb5994c93ff5",
  "time": 41523
}

✅ 补充说明:

  • buildAt 是当前时间(ISO 格式)
  • hash 是 webpack 构建时生成的版本标识
  • time 是构建所用时间,单位是毫秒
  • 你可以按需扩展更多字段(如 Git 提交信息、构建人等)

当然!我们来逐步拆解解释这段写在 vue.config.js 中的 Webpack 插件代码,让你彻底搞清楚每一行是干嘛的,放心改,安心用 😎:


const fs = require('fs')
const path = require('path')

🔹 作用:引入 Node.js 的内置模块,用来:

  • fs: 处理文件写入(用于生成 JSON 文件)
  • path: 构建文件路径,确保跨平台兼容

module.exports = {
  configureWebpack: (config) => {

🔹 作用:这是 Vue CLI 提供的扩展方式,允许你在原始 Webpack 配置基础上添加/修改配置项。


config.plugins.push({

🔹 作用:向 Webpack 插件系统中手动添加一个“匿名插件”,这个插件就是我们自定义的逻辑。


apply: (compiler) => {
 compiler.hooks.done.tap('BuildInfoPlugin', (stats) => {

🔹 作用

  • apply:Webpack 插件的标准接口,会传入 compiler 实例。
  • compiler.hooks.done:Webpack 构建完成时的钩子(此时构建产物已生成)。
  • .tap('BuildInfoPlugin', ...):注册一个处理函数,同时给这个钩子取名为 'BuildInfoPlugin'(便于调试)。

 const info = stats.toJson()

🔹 作用:将构建统计信息(stats)转换成 JS 对象,方便读取如 hash、time 等字段。


const buildInfo = {
   buildAt: new Date().toISOString(),
   hash: info.hash,
   time: info.time
 }

🔹 作用:手动构造一个对象,包含你要写入 JSON 的内容:

  • buildAt: 当前构建时间(ISO 字符串)
  • hash: 本次构建的哈希标识符
  • time: 构建耗时(单位:毫秒)

fs.writeFileSync(
  path.resolve(__dirname, 'dist/build-info.json'),
  JSON.stringify(buildInfo, null, 2),
  'utf-8'
)

🔹 作用

  • 使用 fs.writeFileSync 同步写入 JSON 文件;
  • path.resolve(__dirname, 'dist/build-info.json') 确保写入到 dist/ 目录下;
  • JSON.stringify(..., null, 2) 是格式化输出,带有缩进更易读;
  • 'utf-8' 明确指定文件编码。

          console.log('\n✨ Build info written to dist/build-info.json')

🔹 作用:构建成功后控制台输出一条提示,确保你知道 build info 已成功写入。


🧠 小结

这段代码本质上是自定义了一个 Webpack 插件,监听构建完成事件,并自动将关键信息写入 build-info.json,非常适合做版本追踪、打包监控等场景、前端部署更新依赖。


或者在多插件配置下,抽离配置。可以这样写:

const BuildInfoPlugin = {
  apply: (compiler) => {
    compiler.hooks.done.tap('BuildInfoPlugin', (stats) => {
      const info = stats.toJson()
      const buildInfo = {
        buildAt: new Date().toISOString(),
        hash: info.hash,
        time: info.time, // 单位:ms
      }
      fs.writeFileSync(
        path.resolve(__dirname, 'dist/build-info.json'),
        JSON.stringify(buildInfo, null, 2),
        'utf-8'
      )
      console.log('\n✨ Build info written to dist/build-info.json')
    })
  }
}
module.exports伪代码如下
configureWebpack:config => {
      return {
        plugins: [
         BuildInfoPlugin
        ]
 }

如何将一个git的tag信息一并写入呢?

1️⃣读取 Git Tag 信息
但是存在问题,如果存在对同一个 commit 打多个 Tag 的情况就会出现只读取首次出现的 Tag

const child_process = require('child_process')
function getGitTagOrCommit() {
  try {
    // 优先读取 tag,否则 fallback 到 commit hash
    const tag = child_process.execSync('git describe --tags --always', {
      encoding: 'utf-8'
    }).trim()
    return tag
  } catch (err) {
    return 'unknown'
  }
}

😏原因:
⚠️ 你遇到的这个现象——项目当前是 tag 4.5.6,但脚本却拿到的是 4.5.5,通常有两个典型原因,都是 Git 环境相关的问题。我们来逐个拆解并给出解决方案。


🎯 原因一:你没有 git push --tags

如果你打了 tag:

git tag 4.5.6

没有推送到远程,或者本地其他人打的 tag 没有 fetch 到本地,那么:

git describe --tags

就可能只看到旧的 tag,比如 4.5.5

解决办法

# 把本地 tag 推送到远程仓库
git push --tags

# 确保你本地的 tag 是最新的
git fetch --tags

🎯 原因二:git describe 返回的是上一个已标记的 commit

这是 Git 的默认行为:如果你此刻不是正好停在一个打了 tag 的 commit 上,它就会追溯到最近的 tag。例如:

A---B---C---D (HEAD)
        ↑
       tag: 4.5.5

在这个情况下:

git describe --tags
# 输出:4.5.5-2-gabcdef

说明当前是 4.5.5 后的第 2 个 commit。

解决办法:你需要把 tag 打在当前 commit 上,或者强制指定 HEAD 的 tag。


✅ 更保险的版本号获取方案(推荐)

更新你的代码,强制找出 当前 HEAD 的 tag(如果存在),否则 fallback 到 commit hash:

function getGitTagOrCommit() {
  const child_process = require('child_process')
  try {
    // 获取当前 commit 上是否有 tag
    const exactTag = child_process.execSync(
      'git tag --points-at HEAD',
      { encoding: 'utf-8' }
    ).trim()

    if (exactTag) return exactTag

    // 没有 tag 就 fallback 到 commit hash
    const commit = child_process.execSync(
      'git rev-parse --short HEAD',
      { encoding: 'utf-8' }
    ).trim()

    return commit
  } catch (err) {
    return 'unknown'
  }
}

📦 这样就能更稳定地得到构建时的真实版本,不怕 tag 飘移问题了!

  • 但是此时有可能会输出一个"version": “4.5.5\n4.5.6”,说明你当前的 commit 上同时被打了 多个 tag,所以:
git tag --points-at HEAD

返回了:

4.5.5
4.5.6

每个 tag 一行,自然拼成了字符串 "4.5.5\n4.5.6"


✅ 正确处理方式:只取最新一个 tag 或全部 tag 的数组

你可以根据你的需求来处理:


🟩 方案 A:只取第一个 tag(通常是最新的)

function getGitTagOrCommit() {
  const child_process = require('child_process')
  try {
    const tags = child_process
      .execSync('git tag --points-at HEAD', { encoding: 'utf-8' })
      .trim()
      .split('\n')
      .filter(Boolean)

    if (tags.length > 0) return tags[0]  // 或 tags.at(-1)
    
    const commit = child_process.execSync('git rev-parse --short HEAD', {
      encoding: 'utf-8'
    }).trim()

    return commit
  } catch (err) {
    return 'unknown'
  }
}

🟨 方案 B:存成数组,写入 build-info.json(更完整)

function getGitTagsOrCommit() {
  const child_process = require('child_process')
  try {
    const tags = child_process
      .execSync('git tag --points-at HEAD', { encoding: 'utf-8' })
      .trim()
      .split('\n')
      .filter(Boolean)

    if (tags.length > 0) return tags  // 返回数组

    const commit = child_process.execSync('git rev-parse --short HEAD', {
      encoding: 'utf-8'
    }).trim()

    return [commit]
  } catch (err) {
    return ['unknown']
  }
}

然后写入 build-info.json

const buildInfo = {
  buildAt: new Date().toISOString(),
  hash: info.hash,
  time: info.time,
  version: getGitTagsOrCommit()
}

🔍 示例结果:

{
  "buildAt": "2025-05-07T13:15:00.000Z",
  "hash": "a30cfb5994c93ff5",
  "time": 41523,
  "version": ["4.5.5", "4.5.6"]
}

或者仅取其中一个:

"version": "4.5.6"


网站公告

今日签到

点亮在社区的每一天
去签到