1、新增命令、依賴
//package.json "deploy": "node ./deploy/config.js"
"shelljs": "^0.8.5",
"scp2": "^0.5.0"
2、新增環境變數
# 自動部署
VUE_APP_SERVER_ID = 0
3、新增deploy資料夾
//deploy\config.js
require('shelljs/global');
const inquirer = require('inquirer');
// 釋出的伺服器列表
const ser = require('./servers');
const SERVER_LIST = ser.servers;
inquirer.prompt([{
name: 'conform',
message: '是否需要重新構建?',
type: 'list',
default: 0,
choices: [{name: '是',value: 1}, {name: '否',value: 0}]
},{
name: 'choose',
message: '選擇釋出的環境',
type: 'list',
default: 0,
choices: SERVER_LIST
}]).then(function (answers) {
process.env.VUE_APP_SERVER_ID = answers.choose;
if(answers.choose === 99) {
console.log('取消構建');
return;
}
let cmd = answers.conform ? 'npm run build && node ./deploy' : 'node ./deploy';
exec(cmd);
});
//deploy\index.js
require('shelljs/global');
const ora = require('ora');
const chalk = require('chalk');
const scpClient = require('scp2');
// 釋出的伺服器列表
const ser = require('./servers');
const serverInfo = ser.servers[process.env.VUE_APP_SERVER_ID || 0];
if(!serverInfo) {
return;
}
var Client = require('ssh2').Client;
var conn = new Client();
conn.on('ready', function () {
console.log('Client :: ready');
conn.exec('rm -rf ' + serverInfo.path, function (err,stream) {
if (err) throw err;
stream
.on('close', function (code, signal) {
// 在執行shell命令後,把開始上傳部署專案程式碼放到這裡面
const spinner = ora('準備釋出到伺服器' + serverInfo.name);
spinner.start();
console.log(chalk.green('開始釋出\n'));
scpClient.scp(
'dist/',
{
host: serverInfo.host,
port: serverInfo.port,
username: serverInfo.username,
password: serverInfo.password,
path: serverInfo.path
},
function (err) {
spinner.stop();
if (err) {
console.log(chalk.red('釋出失敗.\n'));
throw err;
} else {
console.log(chalk.green('Success! 成功釋出到' + serverInfo.name + '伺服器! \n'));
}
}
);
conn.end();
})
.on('data', function (data) {
console.log('STDOUT: ' + data);
})
.stderr.on('data', function (data) {
console.log('STDERR: ' + data);
});
});
})
.on('error', (err) => {
console.log(err);
})
.on('end', () => {
console.log('end');
})
.on('close', () => {
console.log('close');
})
.connect({
host: serverInfo.host,
port: serverInfo.port,
username: serverInfo.username,
password: serverInfo.password,
readyTimeout: 5000
});
//deploy\servers.js
/*
* name:自定義名稱
* domain:域名
* host:ip
* port:埠
* username:伺服器賬號
* password:伺服器密碼
* path:釋出到伺服器的指定路徑
*/
const servers = [
{
value: 0,
name: '測試環境41',
domain: '172.19.2.47',
host: '172.19.2.47',
port: '22',
username: 'root',
password: '002@121dsj',
path: '/home/web/rk-unified-portal/dist/'
}
];
module.exports = {
servers: servers
};