vue2、vue3项目打包生成txt文件-自动记录打包日期:git版本、当前分支、提交人姓名、提交日期、提交描述等信息 和 前端项目的版本号json文件

vue2 打包生成text文件 和 前端项目的版本号json文件
  • 项目打包生成txt文件-自动记录git版本、当前分支、提交人姓名、提交日期、提交描述等信息
  • 生成版本号json文件-自动记录当前版本号、打包时间等信息
  • 新建branch-version-webpack-plugin.js文件
js 复制代码
// 同步子进程
const execSync = require('child_process').execSync
const address = require('address')
const needHost = address.ip() || 'localhost' // 需要更改的ip
const fs = require('fs');
const path = require('path');
const moment = require('moment');
// 配置常量
const VERSION_FILES = {
  TXT: 'version.txt',
  JSON: 'version.json'
};
// 时间格式生成
function dateFormat(date) {
  const y = date.getFullYear()
  const M = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
  const d = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
  const h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()
  const m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()
  const s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()
  return `${y}-${M}-${d} ${h}:${m}:${s}`
}
// 读取 package.json 文件
const packagePath = path.resolve(__dirname, '../package.json');
const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));

// 读取或创建版本历史文件
// const versionsPath = path.resolve(__dirname, './versions.json');

// 获取要更新的版本类型 (major, minor, patch) 主修订 次修订 修订号
// npm run build:prod major
console.log( process.argv[3],'process');
// 修订当前的版本号
function updateVersion() {
  const [major, minor, patch] = packageJson.version.split('.').map(Number); 
  if(process.argv[3] === 'major') {
    return `${major + 1}.0.0`;
  }
  if(patch > 20) {
    return `${major}.${minor + 1}.0`;
  }
  return `${major}.${minor}.${patch + 1}`;
}

// 增加修订号(可以根据需要修改为增加主版本号或次版本号)
packageJson.version = updateVersion()
console.log(`版本号已更新为:${packageJson.version}`);

// 更新项目的版本号
function getProjectVersion() {
  return{
   version: packageJson.version,
   buildTime: moment().format('YYYY-MM-DD HH:mm:ss')
  }
}


fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2)); // 写回 package.json
// fs.writeFileSync('./version.json', JSON.stringify(getProjectVersion(), null, 2)); // 写入 version.json

// 格式化日对象
const getNowDate = () => {
  const date = new Date()
  const sign2 = ':'
  const year = date.getFullYear() // 年
  let month = date.getMonth() + 1 // 月
  let day = date.getDate() // 日
  let hour = date.getHours() // 时
  let minutes = date.getMinutes() // 分
  let seconds = date.getSeconds() // 秒
  const weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天']
  // eslint-disable-next-line no-unused-vars
  const week = weekArr[date.getDay()]
  // 给一位数的数据前面加 "0"
  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (day >= 0 && day <= 9) {
    day = '0' + day
  }
  if (hour >= 0 && hour <= 9) {
    hour = '0' + hour
  }
  if (minutes >= 0 && minutes <= 9) {
    minutes = '0' + minutes
  }
  if (seconds >= 0 && seconds <= 9) {
    seconds = '0' + seconds
  }
  return year + '-' + month + '-' + day + ' ' + hour + sign2 + minutes + sign2 + seconds
}

// 获取当前git分支信息
function getBranchVersionInfo() {
  // 当前分支名
  const vName = execSync('git name-rev --name-only HEAD').toString().trim()
  // 提交的commit hash
  const commitHash = execSync('git show -s --format=%H').toString().trim()
  // 提交人姓名
  const name = execSync('git show -s --format=%cn').toString().trim()
  // 提交日期
  const date = dateFormat(new Date(execSync('git show -s --format=%cd').toString()))
  // 提交描述
  const message = execSync('git show -s --format=%s').toString().trim()
  // ip
  const ip = needHost

  const buildDate = getNowDate()
  return `
    buildDate: ${buildDate}\n
    ip地址: ${ip}\n
    当前分支名:${vName}\n
    提交的hash:${commitHash}\n
    提交人姓名:${name}\n
    提交日期:${date}\n
    提交描述:${message}
  `
}
// 创建分支版本类
class BranchVersionWebpackPlugin {
  constructor(options) {
    // options 为调用时传的参数
    // console.log('BranchVersionWebpackPlugin 被调用!', options)
  }
  /**
   * compiler: webpack 的实例 所有的内容
   * compilation: 本次打包的内容
   * */

  apply(compiler) {
    // 异步方法,生成打包目录时:生成文件
    compiler.hooks.emit.tapAsync('BranchVersionWebpackPlugin', (compilation, cb) => {
      // 添加分支版本信息文件
      const branchVersionInfo = getBranchVersionInfo()
      compilation.assets[VERSION_FILES.TXT] = {
        source: () => branchVersionInfo,
        size: () => branchVersionInfo.length
      }
      // 添加前端版本信息文件
      compilation.assets[VERSION_FILES.JSON] = {
        source: () => packageJson.version,
        size: () => branchVersionInfo.length
      }

      cb()
    })
  }
}

module.exports = BranchVersionWebpackPlugin
  • 在vue.config.js文件中引入
js 复制代码
// 分支版本信息 - 引入自定义插件
const BranchVersionWebpackPlugin = require('./webpack-plugin/branch-version-webpack-plugin');

module.exports = {
    ...省略
   configureWebpack: {
    entry:'./src/main.js',//入口
    plugins: [
      new BranchVersionWebpackPlugin()
    ],
    ...省略
  },
}
  • 打包在dist目录下生成的version.txt文件内容如下

    复制代码
      buildDate: 2025-05-16 16:50:44
    
      ip地址: xxxx
    
      当前分支名:dev
    
      提交的hash:xxxx
    
      提交人姓名:xxxxx
    
      提交日期:2025-05-08 11:52:43
    
      提交描述:'1'
  • 打包在dist目录下生成的version.json文件内容如下

json 复制代码
{
  "version": "1.0.0",
  "buildTime": "2025-05-16 16:50:44"
}
vue3 打包生成text文件 和 前端项目的版本号json文件
  • 安装插件
ts 复制代码
npm install moment --save 
npm install address --save
npm install --save-dev @types/address 
npm install --save-dev @types/moment
npm install @types/node --save-dev
  • 新建 branch-version-webpack-plugin.ts
ts 复制代码
// vite-branch-version-plugin.ts
import { execSync } from 'child_process';
import { ip } from 'address';
import type { PluginOption, Plugin } from 'vite';
import moment from 'moment';
import fs from 'fs';
import path from 'path';

const needHost = ip() || 'localhost' // 需要更改的ip地址

// 读取 package.json 文件
const packagePath = path.resolve(__dirname, '../package.json');
const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));

// 修订当前的版本号
function updateVersion() {
    const [major, minor, patch] = packageJson.version.split('.').map(Number); 
    if(process.argv[4] === 'major') {
      return `${major + 1}.0.0`;
    }
    if(patch > 20) {
      return `${major}.${minor + 1}.0`;
    }
    return `${major}.${minor}.${patch + 1}`;
  }
// 更新项目的版本号
// function getProjectVersion() {
//     return{
//      version: packageJson.version,
//      buildTime: moment().format('YYYY-MM-DD HH:mm:ss')
//     }
//   }
  
// 增加修订号(可以根据需要修改为增加主版本号或次版本号)
packageJson.version = updateVersion()
console.log(`版本号已更新为:${packageJson.version}`);
// 写回 package.json 文件
fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2)); // 写回 package.json

// 在根目录写入 version.json
// fs.writeFileSync('./version.json', JSON.stringify(getProjectVersion(), null, 2)); // 写入 version.json


interface PluginOptions {
  filename?: string;
  silent?: boolean;
  VERSION_FILES?: string[];
}
function formatDateTime(date?: any) {
    return {
      iso: moment().format(),
      human: moment(date).format('YYYY-MM-DD HH:mm:ss'),
      buildDate: moment().format('YYYY-MM-DD HH:mm:ss'),
      git: moment(date).format('ddd MMM D HH:mm:ss YYYY Z')
    };
  }
  // 获取当前git分支信息
  function getBranchVersionInfo() {
    // 当前分支名
    const vName = execSync('git name-rev --name-only HEAD').toString().trim()
    // 提交的commit hash
    const commitHash = execSync('git show -s --format=%H').toString().trim()
    // 提交人姓名
    const name = execSync('git show -s --format=%cn').toString().trim()
    // 提交日期
    // const date = dateFormat(new Date(execSync('git show -s --format=%cd').toString()))
    const date = formatDateTime(new Date(execSync('git show -s --format=%cd').toString())).human
    // 提交描述
    const message = execSync('git show -s --format=%s').toString().trim()
    // ip
    const ip = needHost
  
    const buildDate = formatDateTime().buildDate
    return `
      buildDate: ${buildDate}\n
      ip地址: ${ip}\n
      当前分支名:${vName}\n
      提交的hash:${commitHash}\n
      提交人姓名:${name}\n
      提交日期:${date}\n
      提交描述:${message}
    `
  }

export default function BranchVersionPlugin(options?: PluginOptions): PluginOption {
  // 合并默认配置(通过 配置象实现)
  const config = {
    filename: 'version.txt',
    silent: false,
    VERSION_FILES: [
      'version.json', // 项目信息文件
      'version.txt', // 版本信息文件
    ],
    ...options,
   
  };

  return {
    name: 'vite-plugin-branch-version',
   
    // 使用 build 阶段的 generateBundle 钩子
    generateBundle() {
        // 核心 emitFile 调用
        // version.json 生成前端版本信息 - 通过读取package.json文件中version字段 写入
        // version.txt 项目打包生成txt文件-自动记录打包日期:git版本、当前分支、提交人姓名、提交日期、提交描述等信息
        config.VERSION_FILES.forEach(file => {
            this.emitFile({
              type: 'asset',
              fileName: file,
              source: file.endsWith('.json') 
                ? JSON.stringify(packageJson.version, null, 2) 
                : getBranchVersionInfo()
            });
          });
      // 核心 emitFile 调用
    //   this.emitFile({
    //     type: 'asset', //文件类型(asset/chunk)
    //     name: 'version-info',      // 唯一标识名称
    //     fileName: config.filename, // 输出文件名
    //     source: getBranchVersionInfo()            // 文件内容
    //   });
    }
  } as Plugin; // 类型断言确保兼容性
}
  • 在vite.config.ts文件中引入
ts 复制代码
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// 分支版本信息
import BranchVersionPlugin from './webpack-plugin/branch-version-webpack-plugin'
import minimist from 'minimist';
// 解析命令行参数
const argv = minimist(process.argv.slice(2));
console.log(argv, 'argv');

// https://vite.dev/config/
export default defineConfig({
  plugins: [
      vue(), 
      BranchVersionPlugin()],
})
  • 打包在dist 目录下生成的version.txt 和 version.json 文件同上
相关推荐
守城小轩2 小时前
JavaScript vs Python 用于 Web Scraping(2025):终极对比指南
前端·chrome·chrome devtools·指纹浏览器·浏览器开发·超级浏览器
MonkeyKing_sunyuhua4 小时前
项目删除了,为什么vscode中的git还是存在未提交记录,应该怎么删除掉
ide·git·vscode
ao_lang4 小时前
掌握Git:版本控制与高效协作指南
git·学习
风逸hhh4 小时前
python打卡day29@浙大疏锦行
开发语言·前端·python
LuckyLay4 小时前
Vue百日学习计划Day33-35天详细计划-Gemini版
前端·vue.js·学习
ᖰ・◡・ᖳ4 小时前
JavaScript:PC端特效--缓动动画
开发语言·前端·javascript·css·学习·html5
苹果酱05676 小时前
Golang中的runtime.LockOSThread 和 runtime.UnlockOSThread
java·vue.js·spring boot·mysql·课程设计
!win !6 小时前
uni-app项目从0-1基础架构搭建全流程
前端·uni-app
c_zyer6 小时前
使用 nvm 管理 Node.js 和 npm 版本
前端·npm·node.js