webpack项目打包console git分支、打包时间等信息 exec

相关链接

[MDN toLocaleString](#MDN toLocaleString)

[child_process Node.js](#child_process Node.js)

[strftime 格式](#strftime 格式)

代码

buildinfo.js

js 复制代码
const { execSync, exec } = require("child_process");
// exec: 在 Windows 执行 bat 和 cmd 脚本

// execSync 同步
// exec 异步

// exec 使用方法
// exec('git show -s', function(error, stdout, stderr) {
//     if (error) {
//         // ...
//         return
//     }
//     console.log(stdout)
// })

class BuildInfo {
  constructor() {}

  // 当前 git 分支
  branch() {
    // 为什么要使用 `${}`?
    // execSync 返回一个 <Buffer> 数据
    // typeof execSync('ls') -> object
    return this.cleanEmpty(`${execSync("git rev-parse --abbrev-ref HEAD")}`)
  }

  // 本地最新 git 提交 hash
  hash() {
    return this.cleanEmpty(`${execSync("git show -s --format=%H")}`)
  }

  // 本地最新 git 提交记录
  // strftime 格式; 时间格式化参考
  /**
    yyyy: "%Y",
    YYYY: "%Y",
    MM: "%m",
    dd: "%d",
    HH: "%H",
    H: "%I",
    mm: "%M",
    ss: "%S",
    w: "%a",
    W: "%A",
   */
  date() {
    return this.cleanEmpty(`${execute("git log -1 --format=%cd --date=format:%Y-%m-%d %H:%M:%S")}`)
  }

  // 打包时间/本地时间; (仅作参考:本机时间可以被修改)
  // 默认时间格式:2024/3/29 下午4:42:22
  // hour12: 是否使用12小时制格式
  buildtime() {
    return new Date().toLocaleString('zh-cn', { hour12: false })
  }

  // git 输出结果会有换行或空格等字符
  cleanEmpty(s) {
    return s.replace(/[\n\r\s]+$/, '')
  }
}

module.exports = BuildInfo

vue.config.js

js 复制代码
const BuildInfoTools = require('./buildinfo')
const webpack = require('webpack')

const B = new BuildInfoTools()

const plugins = [
    new webpack.DefinePlugin({
        BRANCH: JSON.stringify(B.branch()),
        HASH: JSON.stringify(B.hash()),
        BUILD_TIME: JSON.stringify(B.buildtime())
    })
]


module.exports = {
    lintOnSave: false,
    configureWebpack: {
        plugins
    }
}

入口文件 main.js

js 复制代码
import Vue from 'vue'

new Vue({
    created() {
        console.log(`XXX Branch: ${BRANCH}; last.hash: ${HASH}; Build time: ${BUILD_TIME}`)
    },
    router,
    store,
    render: h => h(App)
}).$mount('#app')
一些问题
  1. 为什么要使用 JSON.stringify()?
    答:不转换会被识别为一个变量
相关推荐
香吧香1 分钟前
GitHub Actions 详解
git
Amos_Web7 分钟前
Rspack 源码解析(三十一):HotModuleReplacementPlugin 如何用 hash 比对生成增量更新
前端
尤水就下18 分钟前
🔥说一说在线文档的 Block 架构是如何实现的
前端·javascript·架构
Madison-No728 分钟前
Git版本控制工具(三)
git
是江迪呀1 小时前
介绍一个开源项目 —— 烂笔头
前端·后端
恋猫de小郭1 小时前
Flutter 紧急发布 3.47.8 安全升级版本,建议都升级
android·前端·flutter
紧跟先前的步伐1 小时前
Go AI Agent 实战 18|Tool Calling 的基本原理与完整执行流程
前端·数据库·人工智能·ai·golang·1024程序员节
captain3761 小时前
Spring Web MVC(2)
java·前端·spring boot·后端·spring·mvc
晓得迷路了1 小时前
栗子前端技术周刊第 151 期 - ViteConf 2026、React Router 8.5、React Native 0.88...
前端·javascript·vue.js
ai工具集合1 小时前
老项目位图图标放大模糊?PNG 一键转 SVG 矢量化实操,附前端避坑指南
前端