Skip to main content

本地脚本自动化部署流程

· 3 min read
石晓波

本地开发项目如果要实现内部部署测试,我们前端开发者每次都需要将打包后的文件交给后端开发人员,然后经过后端开发者部署到服务器。为了简化开发和减少交流成本,也为了提高前端开发者的位置,我们可以编写本地脚本自动化实现打包、测试、部署。也提高我们的工作效率。

如下是实现本地脚本自动化部署流程需要使用的包:

  • shelljs js执行shell脚本
  • rsync 使用 Node.js 构建和执行 rsync 命令的类。
  • colors
  • yargs
scripts/deploy.js
const shell = require('shelljs');
const Rsync = require('rsync');
const path = require('path');
const colors = require('colors');
const argv = require('yargs').argv;
const { exit } = require('process');

//获取执行的进程参数
const [targetName] = argv._;

//设置多台测试机,给每台测试机起代号,对应不同的IP
const host_map = {
staging001: 'onePiece:/root/build'
}

//判断如果不传参数 没有选择要部署的主机 给出提示
if (!host_map[targetName]) {
shell.echo("目标主机不存在!");
shell.exit(1);
}

//设置通知消息 以企业微信为例
function sendNotify(message) {
shell.exec(`curl 'https//qyapi.weixin.qq.com - H 'Content-type:application' - d '{"message": ${message}}`)
}

//0代表成功
// sendNotify('安装依赖')
// console.log(colors.yellow('☕️ 安装依赖'))
// if(shell.exec("npm install").code !== 0){
// shell.echo("error:npm install error.");
// shell.exit(1)
// }

//测试
// sendNotify('进行测试')
// console.log(colors.yellow('☕️ 进行测试'))
// if(shell.exec("npm run test").code !== 0){
// shell.echo("error:npm run test error.");
// shell.exit(1)
// }
//构建
sendNotify('开始构建')
console.log(colors.yellow('☕️ 开始构建'))
if(shell.exec("npm run build").code !== 0){
shell.echo("error:npm run build error.");
shell.exit(1)
}

//部署
sendNotify("开始部署")
console.log(colors.yellow('☕️ 开始部署'));
const rsync = Rsync.build({
source:path.join(__dirname,'../','/./build/*'),
destination: host_map[targetName],
flags:'avz',
shell:'ssh'
})

rsync.execute(function(error, code, cmd) {
console.log(error,code,cmd,)
console.log(colors.yellow('☕️ 部署完成'))
sendNotify('部署完成')
});

如上所示注释了安装依赖的步骤,本地开发环境不需要重新安装依赖,可以节省掉安装依赖的时间。需要注意的是建议配置免密登录,要不然需要手动输入密码体验差。

执行优化

如上要运行脚本需要使用node命令去执行对应的脚本文件,可以配置package.json的scripts

"scripts":{
"deploy": "node ./scripts/deploy.js"
}

扩展:也可以将本地脚本自动化部署写成npm包,通过配置主机的方式,命令执行部署