banner
白澪

星象庄园笔记

twitter
github
telegram
youtube
bilibili

「NodeJS」在前端展示構建及Git提交信息

在寫項目的時候,白澪想到了之前看到別的項目網頁上,有展示提交 hash構建時間。所以自己也想在項目中展示這些信息 φ(゜▽゜ *)♪
tips> 這是白澪自己的想法,因為實在也沒有找到別人的示範(其實也是懶得翻源碼),就自己做了實現

獲取構建和 Git 信息,,ԾㅂԾ,,#

白澪的想法是構建之前通過腳本執行命令並解析獲取數據,所以首先要創建一個腳本,白澪一般放在以下的路徑 script/generate-build-info.js

  1. 首先需要一個執行命令的函數 △□○(´▽`)
const { execSync } = require('child_process');

/**
 * 安全執行命令,避免出錯時直接崩潰
 * @param {string} command - 命令
 * @param {string} fallback - 出錯時的默認返回值
 * @returns {string} 命令執行結果或默認值
 */
function exec(command, fallback = 'unknown') {
  try {
    return execSync(command).toString().trim()
  } catch (error) {
    console.warn(`Shell Command Failed: ${command}`, error.message)
    return fallback
  }
}
  1. 其次使用命令構建包含所需信息的對象 (☆▽☆) 下面是一個小示範
const buildInfo = {
  version: projectInfo.version, // 這裡的projectInfo是通過path模塊打開package.json文件獲取數據
  hash: exec('git rev-parse --short HEAD'),
  hashFull: exec('git rev-parse HEAD'),
  summary: exec('git log -1 --pretty=%s'),  // 只獲取摘要
  
  buildDate: new Date().toISOString(),
  buildTimestamp: Date.now(),
  nodeVersion: process.version,
  platform: process.platform
};
  1. 將對象輸出成含導出的 JS 文件,讓前端獲取數據 (●ˇ∀ˇ●)
// 將對象轉換為字符串
const content = `/**
 * Automatically generated build information (。^▽^)
 *
 * This file is automatically generated by the \`generate-build-info.js\` script,
 * only used to provide build information for the project!
 *
 * Script author: 白澪·洛絲塔亞(mio@chyan.moe)
 *
 * File created on : ${new Date().toISOString()}
 */

export const buildInfo = ${JSON.stringify(buildInfo, null, 2)}` // 當然這一行才是重點(。^▽^)

// 寫入文件
const __rootdir = process.cwd()
const outputPath = path.resolve(__rootdir, 'src/build-info.js')
fs.writeFileSync(outputPath, content)

生成腳本文件到此就已經寫好了~

使用構建信息 (。>︿<)_θ#

生成的信息長這樣 ○(^皿^) っ CodeCodeCode......

/**
 * Automatically generated build information (。^▽^)
 *
 * This file is automatically generated by the `generate-build-info.js` script,
 * only used to provide build information for the project!
 *
 * Script author: 白澪·洛絲塔亞(mio@chyan.moe)
 *
 * File created on : 2025-05-04T16:00:45.517Z
 */

export const buildInfo = {
  "git": {
    "repository": "https://github.com/Miourasaki/kagamie.git",
    "commit": {
      "hash": "427caef",
      "hashFull": "427caef417aa15e3260beb41335dc9d5f8e43296",
      "message": "feat(draw): 新增橡皮工具\n\n變更包括:\n - 👚放大後不再隱藏鼠標,更加容易定位\n - ✏️新增工具:橡皮 可以清除像素點",
      "summary": "feat(draw): 新增橡皮工具",
      "description": "變更包括:\n - 👚放大後不再隱藏鼠標,更加容易定位\n - ✏️新增工具:橡皮 可以清除像素點",
      "date": "Mon May 5 00:00:34 2025 +0800",
      "author": "白澪 · 洛絲塔亞",
      "authorEmail": "mio@chyan.moe"
    },
    "branch": "master",
    "tag": "427caef"
  },
  "buildDate": "2025-05-04T16:00:45.514Z",
  "buildTimestamp": 1746374445517,
  "node": {
    "version": "v20.14.0",
    "project": {
      "name": "kagamie",
      "version": "0.1.0.0"
    }
  },
  "platform": "win32"
}

使用時這麼做在 ES Module

import { buildInfo } from '../src/build-info'

大致思路就是這樣啦。大功告成。 ヾ (≧▽≦*) o
來看看效果

這是參考圖,使用效果在 RinnTaya/KagamiE 這個項目上
參考圖
對了也可以來看看白澪的這個項目 (。・・) ノ —— 大家一起來茶繪~

以上,最後大家可以參考白澪的代碼片段 # generate-build-info.js ヾ (≧▽≦*) o

此文由 Mix Space 同步更新至 xLog
原始鏈接為 https://rinn.im/posts/web/nodejs/generate-build-info.js


載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。