使用 gulp gulp-ssh 自动上传代码

使用 gulp gulp-ssh 自动上传代码

1. 安装 gulp 和 gulp

 npm i gulp gulp-ssh -save -dev

2. 创建 配置文件

npm 配置文件

"scripts": {
    "deploy:test": "npm run test && gulp deploy"
  },
  deploy // 创建任务的名称
const gulp = require('gulp')
const GulpSSH = require('gulp-ssh')


const { APP_ENV, npm_package_name } = process.env;
const isProduct = APP_ENV === 'production';

// 需要上传到服务器的路径
const remotePath = `/home/public/docker/main/${npm_package_name}`
const config = {
  ssh: { // 正式
    host: isProduct ? '' : '192.168.31.227',
    port: isProduct ? 22 : 8822,
    username: 'root',
    password: isProduct ? '' : 'a1234567',
  },
  remotePath,
  commands: [
    // 删除现有文件
    `rm -rf ${remotePath}`,
  ],
}
const gulpSSH = new GulpSSH({
  ignoreErrors: false,
  sshConfig: config.ssh,
})
/**
 * 上传前先删除服务器上现有文件...
 */
 gulp.task('execSSH', () => {
  console.log('删除服务器上现有文件...')
   return gulpSSH.shell(config.commands, { filePath: 'commands.log' })
   .pipe(gulp.dest('logs'))
 })
/**
 * 上传文件到服务器
 */

gulp.task('deploy', gulp.series('execSSH', done => {
  console.log('2s后开始上传文件到服务器...')
  setTimeout(() => {
    gulp.src(`./${npm_package_name}/**`)
    .pipe(gulpSSH.dest(config.remotePath))
    console.log('上传完毕.....')
    done();
  }, 2000)
}))

posted @ 2022-11-15 16:57  过好每一天2022  阅读(162)  评论(0)    收藏  举报