vue2 打包生成text文件 和 前端项目的版本号json文件
- 项目打包生成txt文件-自动记录git版本、当前分支、提交人姓名、提交日期、提交描述等信息
- 生成版本号json文件-自动记录当前版本号、打包时间等信息
- 新建branch-version-webpack-plugin.js文件
const execSync = require('child_process').execSync
const address = require('address')
const needHost = address.ip() || 'localhost'
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}`
}
const packagePath = path.resolve(__dirname, '../package.json');
const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
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));
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 = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天']
const week = weekArr[date.getDay()]
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
}
function getBranchVersionInfo() {
const vName = execSync('git name-rev --name-only HEAD').toString().trim()
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()
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) {
}
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
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文件内容如下
{
"version": "1.0.0",
"buildTime": "2025-05-16 16:50:44"
}
vue3 打包生成text文件 和 前端项目的版本号json文件
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
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'
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}`;
}
packageJson.version = updateVersion()
console.log(`版本号已更新为:${packageJson.version}`);
fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2));
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')
};
}
function getBranchVersionInfo() {
const vName = execSync('git name-rev --name-only HEAD').toString().trim()
const commitHash = execSync('git show -s --format=%H').toString().trim()
const name = execSync('git show -s --format=%cn').toString().trim()
const date = formatDateTime(new Date(execSync('git show -s --format=%cd').toString())).human
const message = execSync('git show -s --format=%s').toString().trim()
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',
generateBundle() {
config.VERSION_FILES.forEach(file => {
this.emitFile({
type: 'asset',
fileName: file,
source: file.endsWith('.json')
? JSON.stringify(packageJson.version, null, 2)
: getBranchVersionInfo()
});
});
}
} as Plugin;
}
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');
export default defineConfig({
plugins: [
vue(),
BranchVersionPlugin()],
})
- 打包在dist 目录下生成的version.txt 和 version.json 文件同上