vite项目实现代码编译后自动上传服务器

235 阅读1分钟
  1. 项目根目录下创建deploy.js
  2. 安装node-ssh、path 和dayjs
  3. 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()

// 获取当前文件的目录名,ESM 中没有 __dirname,需要通过 `import.meta.url` 来实现
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', // 服务器 IP
  username: 'your_username', // 服务器用户名
  password: 'your_password', // 服务器密码 (可以改成私钥路径以使用 SSH Key)
}

// 连接服务器并执行部署
ssh
  .connect(config)
  .then(async () => {
    try {
      // Step 1: 备份远程服务器的目录
      console.log(`Backing up ${serverDir} to ${backupDir}`)
      await ssh.execCommand(`cp -r ${serverDir} ${backupDir}`)
      console.log('Backup completed.')

      // Step 2: 上传本地打包文件到远程服务器
      console.log('Uploading files...')
      await ssh.putDirectory(distDir, serverDir)
      console.log('Files uploaded successfully.')

      // Step 3: 断开连接
      ssh.dispose()
    } catch (error) {
      console.error('Error during deployment:', error)
    }
  })
  .catch((err) => {
    console.error('SSH connection error:', err)
  })