#!/usr/bin/env node /** * 前端部署脚本 - 自动化部署Vue应用 */ const { execSync } = require('child_process'); const fs = require('fs'); const path = require('path'); // ANSI颜色代码 const colors = { reset: '\x1b[0m', red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', blue: '\x1b[34m', magenta: '\x1b[35m', cyan: '\x1b[36m' }; function log(message, color = 'reset') { console.log(`${colors[color]}${message}${colors.reset}`); } function runCommand(command, description) { log(`\n${'='.repeat(50)}`, 'cyan'); log(`执行: ${description}`, 'cyan'); log(`命令: ${command}`, 'cyan'); log(`${'='.repeat(50)}`, 'cyan'); try { const output = execSync(command, { stdio: 'inherit', encoding: 'utf-8', cwd: process.cwd() }); log(`✅ ${description} - 成功`, 'green'); return true; } catch (error) { log(`❌ ${description} - 失败`, 'red'); log(`错误: ${error.message}`, 'red'); return false; } } function checkFile(filePath, description) { if (fs.existsSync(filePath)) { log(`✅ ${description} - 存在`, 'green'); return true; } else { log(`❌ ${description} - 不存在`, 'red'); return false; } } function deploy() { log('🚀 开始部署企业级日报系统前端...', 'magenta'); // 1. 检查Node.js版本 if (!runCommand('node --version', '检查Node.js版本')) { return false; } // 2. 检查npm版本 if (!runCommand('npm --version', '检查npm版本')) { return false; } // 3. 检查package.json if (!checkFile('package.json', '检查package.json文件')) { return false; } // 4. 安装依赖 log('\n📦 安装项目依赖...', 'yellow'); if (!runCommand('npm install', '安装npm依赖')) { return false; } // 5. 代码检查 log('\n🔍 执行代码检查...', 'yellow'); if (!runCommand('npm run lint', '代码检查和格式化')) { log('⚠️ 代码检查失败,但继续部署...', 'yellow'); } // 6. 构建生产版本 log('\n🏗️ 构建生产版本...', 'yellow'); if (!runCommand('npm run build', '构建生产版本')) { return false; } // 7. 检查构建结果 if (!checkFile('dist', '检查构建输出目录')) { return false; } // 8. 显示构建统计 log('\n📊 构建统计信息:', 'cyan'); try { const distPath = path.join(process.cwd(), 'dist'); const files = fs.readdirSync(distPath, { withFileTypes: true }); files.forEach(file => { if (file.isFile()) { const filePath = path.join(distPath, file.name); const stats = fs.statSync(filePath); const size = (stats.size / 1024).toFixed(2); log(` - ${file.name}: ${size} KB`, 'blue'); } }); } catch (error) { log('无法读取构建统计信息', 'yellow'); } log('\n🎉 前端部署完成!', 'green'); log('\n📋 部署信息:', 'cyan'); log('- 构建输出: ./dist/', 'cyan'); log('- 开发服务器: npm run serve', 'cyan'); log('- 生产构建: npm run build', 'cyan'); log('- 代码检查: npm run lint', 'cyan'); log('\n🌐 部署到服务器:', 'cyan'); log('1. 将 dist/ 目录上传到Web服务器', 'cyan'); log('2. 配置Nginx反向代理到后端API', 'cyan'); log('3. 确保API地址配置正确', 'cyan'); return true; } // 主函数 async function main() { try { const success = deploy(); process.exit(success ? 0 : 1); } catch (error) { log(`\n\n❌ 部署失败: ${error.message}`, 'red'); process.exit(1); } } // 处理中断信号 process.on('SIGINT', () => { log('\n\n⚠️ 部署被用户中断', 'yellow'); process.exit(1); }); process.on('SIGTERM', () => { log('\n\n⚠️ 部署被系统终止', 'yellow'); process.exit(1); }); // 运行主函数 if (require.main === module) { main(); } module.exports = { deploy };