const fs = require('fs'); const path = require('path'); function changeVersion() { // 直接读取.env文件中的版本号 const envPath = path.join(__dirname, '.env'); let version = '1.0.0'; // 默认版本号 if (fs.existsSync(envPath)) { const fileContent = fs.readFileSync(envPath, 'utf-8'); const versionMatch = fileContent.match(/VITE_APP_VERSION\s*=\s*([^\r\n]+)/); if (versionMatch && versionMatch[1]) { version = versionMatch[1].trim(); } } let newVersion; if (version) { // 将版本号按点号分割 const parts = version.split('.'); const lastPart = parts[parts.length - 1]; // 查找最后一部分中的数字 const numberMatch = lastPart.match(/(\d+)([^\d]*)$/); if (numberMatch) { // 递增数字部分 const number = parseInt(numberMatch[1]) + 1; const suffix = numberMatch[2] || ''; // 非数字后缀 // 替换最后一部分中的数字 parts[parts.length - 1] = lastPart.replace(/(\d+)([^\d]*)$/, number + suffix); } else { // 如果最后一部分没有数字,则添加.1 parts.push('1'); } newVersion = parts.join('.'); } else { // 如果没有找到版本号,使用默认值 newVersion = '1.0.1'; } // 修改版本号 if (fs.existsSync(envPath)) { const file = fs.readFileSync(envPath, 'utf-8'); // 使用正则表达式更可靠地替换版本号 const versionRegex = /VITE_APP_VERSION\s*=\s*.*/; const newVersionLine = `VITE_APP_VERSION=${newVersion}`; const result = file.replace(versionRegex, newVersionLine); // 同步写文件 fs.writeFileSync(envPath, result, 'utf-8'); } return newVersion; } module.exports = changeVersion;