- 项目根目录下创建
deploy.js;
- 安装
node-ssh、path 和dayjs;
package.json新增命令"build:test-deploy": "vite build --mode test && node deploy.js";
import { NodeSSH } from 'node-ssh'
import path from 'path'
import dayjs from 'dayjs'
import { fileURLToPath } from 'url'
const ssh = new NodeSSH()
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const now = dayjs()
const distDir = path.resolve(__dirname, 'dist')
const backupDir = `/apps/nginx/www/backup/agency_backup_${now.format('YYYY-MM-DD_HH:mm:ss')}`
const serverDir = '/apps/nginx/www/agency'
const config = {
host: 'your.server.ip',
username: 'your_username',
password: 'your_password',
}
ssh
.connect(config)
.then(async () => {
try {
console.log(`Backing up ${serverDir} to ${backupDir}`)
await ssh.execCommand(`cp -r ${serverDir} ${backupDir}`)
console.log('Backup completed.')
console.log('Uploading files...')
await ssh.putDirectory(distDir, serverDir)
console.log('Files uploaded successfully.')
ssh.dispose()
} catch (error) {
console.error('Error during deployment:', error)
}
})
.catch((err) => {
console.error('SSH connection error:', err)
})