gulp 实现简单的自动化部署
平时在开发时,打包完之后需要把项目部署到测试线上,平时我们要么用 filezilla 有图形界面的工具拖拽上传,要么用 Xshell 这种无图形界面的工具向服务器上传文件。
但是有没有一种直接办法可以直接一行代码命令上传,方便简洁免登录呢。
最终我发现可以使用 gulp 进行简单的自动化部署。
需要安装插件 gulp 以及 gulp-ssh
新建 gulpfile.js 文件:
var gulp = require('gulp'),
GulpSSH = require('gulp-ssh');
var localDirectory = 'xxx', //打包文件的名称
workDirectory = '/xx/xx/xx', //服务器地址
commands = 'rm -f ' + workDirectory; //删除文件命令
var gulpSSH = new GulpSSH({
ignoreErrors: false,
sshConfig: {
"host": "xxx.xxx.xxx.xxx", //服务器host
"port": "xxxx", //服务器端口
"username": "xxx", //登陆服务器账号
"password": "xxx" //登陆服务器密码
}
});
使用了 GulpSSH 插件打开服务器,并登录。
//文件上传到远程服务器
gulp.task('upload',async function() {
console.log('******************************')
console.log('**********开始上传文件*********')
console.log('******************************')
//只能根据对应文件夹上传,如需添加文件夹则要新增文件夹路径
await gulp.src(localDirectory + '/*',{ buffer: false }).pipe(gulpSSH.dest(workDirectory + '/'))
await gulp.src(localDirectory + '/static/*',{ buffer: false }).pipe(gulpSSH.dest(workDirectory + '/static/'))
await gulp.src(localDirectory + '/static/js/*',{ buffer: false }).pipe(gulpSSH.dest(workDirectory + '/static/js/'))
await gulp.src(localDirectory + '/static/css/*',{ buffer: false }).pipe(gulpSSH.dest(workDirectory + '/static/css/'))
});
这里使用了 async ,考虑上传时异步操作无法实时监控。
//清除远程服务器文件
gulp.task('del', async function() {
console.log('************************************')
console.log('**********删除服务器上现有文件********')
console.log('************************************')
await gulpSSH.shell(commands + '/index.html');
await gulpSSH.shell(commands + '/static/*');
await gulpSSH.shell(commands + '/static/js/*');
await gulpSSH.shell(commands + '/static/css/*');
});
这样,只要在 cmd 使用命令:
gulp del //删除远程服务器上的文件
gulp upload //把项目上传至远程服务器
就可以完成简单的自动化部署。
当然,更复杂的貌似可以通过 node.js 自己写一套连接 ssh 上传的脚本而不是用现有模块达成。目前我是没试过,就不过多讲了。