脚本部署
背景
Jenkins
出了点问题,而且每次打包时间太久。这段时间代码每次都没有及时更新到测试环境,导致测试测出了各种问题。而且通过 Xshell
去更改代码,比较繁琐,总容易遗忘。(特别是快下班的时候)
既然我们的前端环境包含了 node
为什么不直接通过 node
实现上传打包后的代码呢。
实现
- 引入
node-ssh
- 建立连接
- 复制文件夹
- 关闭连接
基础几步,基本没有太大难度。 node-ssh
的 README 基本上就可以实现啦。
/**
* @file: deploy.js
* @author: duanjl
* @date: 2019/8/6
* @description: 通过node-ssh提交build后的代码
* */
// eslint-disable-next-line
const NodeSSH = require('node-ssh');
// const open = require('open'); // 可以用来打开浏览器
const ssh = new NodeSSH();
const localDir = './build';
const remoteDir = '/opt/front-end';
const removeCommand = 'rm -rf ./build';
const host = 'localhost';
const password: '****',
// 新建连接
ssh.connect({
host,
username: 'front',
port: 22,
password,
privateKey: '/home/.ssh/***',
})
.then(() => {
// 删除原目录
ssh.execCommand(removeCommand, { cwd: remoteDir }).then((result) => {
// 可以通过返回值,做一些简单的判断,来实现某些分支流程
console.log(`STDOUT: ${result.stdout}`);
console.log(`STDERR: ${result.stderr}`);
// 提交指定目录
ssh.putDirectory(localDir, `${remoteDir}/build`).then(
() => {
console.log('The File thing is done');
ssh.dispose();
// open(`http://${host}`, { app: ['chrome'] });
},
(error) => {
console.log("Something's wrong");
console.log(error);
ssh.dispose();
},
);
});
});
这里,我删除原目录的时候,是在 build 目录的父级目录下,指定删除 build 目录。防止我哪天不小心将远端目录指定到了某个根目录....
借助 open
包,我们可以在传输完成之后,自动打开浏览器。
more
如果我们考虑的更多一点,提交到多个服务器呢。
/**
* @file: deploy.js
* @author: duanjl
* @date: 2019/8/6
* @description: 通过node-ssh提交build后的代码
* */
// eslint-disable-next-line
const NodeSSH = require('node-ssh');
// const open = require('open'); // 可以用来打开浏览器
const ssh = new NodeSSH();
const localDir = './build';
const remoteDir = '/opt/front-end';
const removeCommand = 'rm -rf ./build';
const hostWithPasswordArr = [
{
host: 'localhost',
password: '****',
},
];
// 遍历多个数组
hostWithPasswordArr.forEach((hostWithPassword) => {
const { host, password } = hostWithPassword;
ssh.connect({
host,
username: 'root',
port: 22,
password,
}).then(() => {
ssh.execCommand(removeCommand, { cwd: remoteDir }).then((result) => {
console.log(`STDOUT: ${result.stdout}`);
console.log(`STDERR: ${result.stderr}`);
ssh.putDirectory(localDir, `${remoteDir}/build`).then(
() => {
console.log('The File thing is done');
ssh.dispose();
},
(error) => {
console.log("Something's wrong");
console.log(error);
ssh.dispose();
},
);
});
});
});
通过数组遍历,我们就可以实现提交到多个服务器了。不过一定要记得关闭连接哦。
使用脚本
最后一步,就是使用脚本。在 package.json
中, scripts
中加上一条。
"deploy": "npm run build && node ./deploy.js",
再打包完之后,执行部署的操作。
为什么不直接复写到build命令呢? 因为经常会需要打各种环境的包,可能是改一个url,可能是去掉某个提示,可能是隐藏一些菜单,满足在不同环境下的需求。这种代码更改,并不应该出现在测试服务器上。
能不能在git提交后,就自动打包并部署呢? 借助
husky
,应该可以实现在提交代码后部署至远端。
提示
因为文件中包含有服务器密码等敏感数据,最好不要上传到 gi t哦~