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()?
    答:不转换会被识别为一个变量
相关推荐
GISer_Jing1 小时前
前端面试通关:Cesium+Three+React优化+TypeScript实战+ECharts性能方案
前端·react.js·面试
落霞的思绪2 小时前
CSS复习
前端·css
咖啡の猫4 小时前
Shell脚本-for循环应用案例
前端·chrome
百万蹄蹄向前冲7 小时前
Trae分析Phaser.js游戏《洋葱头捡星星》
前端·游戏开发·trae
朝阳5817 小时前
在浏览器端使用 xml2js 遇到的报错及解决方法
前端
GIS之路7 小时前
GeoTools 读取影像元数据
前端
ssshooter8 小时前
VSCode 自带的 TS 版本可能跟项目TS 版本不一样
前端·面试·typescript
Jerry9 小时前
Jetpack Compose 中的状态
前端
百思可瑞教育9 小时前
Git 对象存储:理解底层原理,实现高效排错与存储优化
大数据·git·elasticsearch·搜索引擎
dae bal9 小时前
关于RSA和AES加密
前端·vue.js