node 输出版本git信息 并显示在浏览器控制台

文章描述了一个在项目根目录下创建version.js文件的过程,该文件用于获取当前的Git信息如编译时间、执行人、分支、commit等,并将这些信息写入version.txt和versionLog.js。在Angular项目的build和start命令前调用nodeversion.js,确保每次构建或启动时更新这些信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,根路径下创建version.js文件,内容为以下

const fs = require('fs');
const execSync = require('child_process').execSync;
const execGitCmd = cmd => execSync(cmd).toString().replace(/\n$/, '');

// git相关信息
const date = new Date().toLocaleString(); // 编译时间
const user = execGitCmd('git config user.name'); // 编译执行人名称
const email = execGitCmd('git config user.email'); // 编译执行人邮箱
const gitBranch = execGitCmd(`git symbolic-ref --short -q HEAD`); // git 分支
const commit = execGitCmd(`git log -n 1 --pretty=format:"%H"`); // 最近commit
const info = execGitCmd('git log --abbrev-commit -1'); // 最近1次 git 提交信息

try {
  const versionStr = `
环境:    ${process.env.NODE_ENV || '--'}
编译时间:${date}
执行人:  ${user} <${email}>
分支:    ${gitBranch}
commitId:${commit}

最后提交信息:
${info}
  `;

  const group = `console.group('版本信息');`;
  const allInfo = `console.log(${JSON.stringify(versionStr)});`;

  const output = `
${group}
${allInfo}
  `

  console.log(versionStr)
  fs.writeFileSync(`version.txt`, versionStr);
  fs.writeFileSync('versionLog.js', output, err => {
    if (err) console.log(err)
  })
} catch (e) {
  throw new Error(e);
}

二,根路径下创建 versionLog.js 文件

        入口文件main.ts 引入

import '../versionLog';

三,build和start命令前加上node version.js &&

    "start": "node version.js && node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/ng serve --port 4206 --host 0.0.0.0 --optimization=false",
    "build": "node version.js && node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/ng build --prod --output-hashing=all --optimization=false",

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值