由于项目频繁更新版本,很是麻烦,于是就想到了自动化部署,之前有用到jekins,但是由于现在项目少,就没有费劲去部署jekins,于是想到的别的自动化部署的方式。
1. 项目中新建deploy.js文件,内容如下
const { NodeSSH } = require("node-ssh");
const path = require('path');
const log = console.log;
const env = process.argv.slice(2)[0];
const { local, remote, clientConfig } = (() => {
if(env === 'test') {
return {
local: path.resolve(__dirname, './dist'), //本地 待发布目标
remote: 'xxx',//服务器 发布地址
clientConfig: {
port: 22, // ssh 端口
host: 'xxx',// ssh 地址
username: 'root',// ssh 用户
password: 'xxx', // 密码
},
}
}else if(env === 'prod') {
return {
local: path.resolve(__dirname, './dist'), //本地 待发布目标
remote: 'xxx',//服务器 发布地址
clientConfig: {
port: 22, // ssh 端口
host: 'xxx',// ssh 地址
username: 'root',// ssh 用户
password: 'xxx', // 密码
},
}
}
})();
async function init() {
//实例化node服务器连接协议
const client = new NodeSSH();
//连接服务器, connect获取连接信息
let connect = await client.connect(clientConfig);
//判断是否连接成功
let isConnected = client.isConnected();
if (isConnected) {
log('----------------------连接成功----------------------')
// 删除对应目录下的所有文件
await client.execCommand('rm -rf *', { cwd: remote })
log('----------------------删除文件成功----------------------')
const status = await client.putDirectory(local, remote, {
recursive: true,
concurrency: 10,
tick: function(localPath, remotePath, error) {
console.log('tick is>>>>>>>>>', localPath, remotePath, error)
}
});
//成功为true
status?console.warn('=================部署成功==================') : console.warn('============部署失败====================')
process.exit(0)
}
};
init()
2. 配置package.json打包命令如下
"build:test": "umi build && node deploy test",
"build:prod": "umi build && node deploy prod",