安装依赖包
npm i shelljs ssh2-sftp-client --save-dev
在项目根目录新建 upload 文件夹config.js、index.js 和备份文件夹 dist1
在package.json添加 upload 命令
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"upload": "node upload/index.js"
},
config.js
module.exports = [
{
ip: "xxxxxx",
username: 'xxxxx',
port: '22',
password: 'xxxxxx',
path: '/xxx/xxx',
rmovepath: '/xxx/xxx'
}
];
index.js
const config = require('./config.js');
const shell = require('shelljs');
const path = require('path');
const Client = require('ssh2-sftp-client');
const compileDist = async () => {
if (shell.exec(`npm run build`).code === 0) {
console.log('打包成功');
}
};
async function connectShell() {
config.map(item => {
const sftp = new Client();
sftp.connect({
host: item.ip,
port: item.port,
username: item.username,
password: item.password
}).then(() => {
console.log('先执行拉下文件备份');
return sftp.downloadDir(item.path, path.resolve('__dirname', `../dist1/${item.ip}`));
}).then(() => {
console.log('执行删除文件');
return sftp.rmdir(item.path, true);
}).then(() => {
console.log('执行上传文件');
return sftp.uploadDir(path.resolve('__dirname', '../dist'), item.path);
}).then(() => {
console.log('上传完成');
sftp.end();
}).catch((err) => {
console.log(err, '上传失败');
sftp.end();
});
});
}
async function runStart() {
await compileDist();
await connectShell();
}
runStart();
执行命令打包自动部署
npm run upload