OL-LearnPlatform/deploy.js

108 lines
2.7 KiB
JavaScript
Raw Normal View History

2025-08-01 01:22:09 +08:00
#!/usr/bin/env node
/**
* 部署脚本 - 自动配置环境变量和构建项目
*/
const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')
console.log('🚀 开始部署流程...')
// 检查是否有真实的API服务器
async function checkApiServer(apiUrl) {
try {
const fetch = (await import('node-fetch')).default
const response = await fetch(`${apiUrl}/health`, {
timeout: 5000,
method: 'GET'
})
return response.ok
} catch (error) {
console.log(`❌ API服务器检查失败: ${error.message}`)
return false
}
}
// 读取环境配置
function readEnvFile(filePath) {
if (!fs.existsSync(filePath)) {
return {}
}
const content = fs.readFileSync(filePath, 'utf8')
const env = {}
content.split('\n').forEach(line => {
const trimmed = line.trim()
if (trimmed && !trimmed.startsWith('#')) {
const [key, ...valueParts] = trimmed.split('=')
if (key && valueParts.length > 0) {
env[key.trim()] = valueParts.join('=').trim()
}
}
})
return env
}
// 写入环境配置
function writeEnvFile(filePath, env) {
const content = Object.entries(env)
.map(([key, value]) => `${key}=${value}`)
.join('\n')
fs.writeFileSync(filePath, content + '\n')
}
async function main() {
// 读取生产环境配置
const prodEnv = readEnvFile('.env.production')
const apiUrl = prodEnv.VITE_API_BASE_URL
if (apiUrl) {
console.log(`🔍 检查API服务器: ${apiUrl}`)
const isApiAvailable = await checkApiServer(apiUrl.replace('/api', ''))
if (isApiAvailable) {
console.log('✅ API服务器可用使用真实API')
prodEnv.VITE_ENABLE_MOCK = 'false'
} else {
console.log('❌ API服务器不可用启用Mock模式')
prodEnv.VITE_ENABLE_MOCK = 'true'
}
} else {
console.log('⚠️ 未配置API地址启用Mock模式')
prodEnv.VITE_ENABLE_MOCK = 'true'
}
// 更新生产环境配置
writeEnvFile('.env.production', prodEnv)
console.log('📝 已更新生产环境配置')
// 构建项目
console.log('🔨 开始构建项目...')
try {
execSync('npm run build', { stdio: 'inherit' })
console.log('✅ 构建完成!')
// 显示部署信息
console.log('\n📋 部署信息:')
console.log(` Mock模式: ${prodEnv.VITE_ENABLE_MOCK === 'true' ? '启用' : '禁用'}`)
if (apiUrl) {
console.log(` API地址: ${apiUrl}`)
}
console.log(' 构建文件: ./dist/')
} catch (error) {
console.error('❌ 构建失败:', error.message)
process.exit(1)
}
}
main().catch(error => {
console.error('❌ 部署失败:', error)
process.exit(1)
})