安装scp2
npm install scp2 --save-dev
npm install --save-dev cross-env
package.json
“deploy:prod”: “npm run build && cross-env NODE_ENV=prod node ./yirenck”,
跟目录建立yirenck文件夹
里面建立文件 index.js products.js
index.js
// yirenck/index.js里面
const scpClient = require("scp2");
const ora = require("ora");
const chalk = require("chalk");
const server = require("./products");
// console.log('server',server);
// const spinner = ora(
// '正在发布到' +
// (process.env.NODE_ENV === 'production' ? '生产' : '测试') +
// '服务器...'
// );
console.log(
chalk.green(
"正在发布到" +
(process.env.NODE_ENV === "production" ? "生产" : "测试") +
"服务器..."
)
);
var Client = require("ssh2").Client;
var conn = new Client();
// 在执行shell命令后,把开始上传部署项目代码放到这里面
console.log("server", server);
scpClient.scp(
"./dist",
{
host: server.host,
port: server.port,
username: server.username,
password: server.password,
path: server.path,
},
function(err) {
// spinner.stop();
if (err) {
console.log(chalk.red("发布失败.\n"));
throw err;
} else {
console.log(
chalk.green(
"Success! 成功发布到" +
(process.env.NODE_ENV === "production" ? "生产" : "测试") +
"服务器! \n"
)
);
}
}
);
products.js
/*
*读取env环境变量
*/
const fs = require("fs");
const path = require("path");
// env 文件 判断打包环境指定对应的服务器id
const envfile = process.env.NODE_ENV === "prod" ? "../.env" : "../.env";
// env环境变量的路径
const envPath = path.resolve(__dirname, envfile);
// env对象
const envObj = parse(fs.readFileSync(envPath, "utf8"));
console.log("envObj", envObj);
const SERVER_ID = parseInt(envObj["VUE_APP_SERVER_ID"]);
function parse(src) {
// 解析KEY=VAL的文件
const res = {};
src.split("\n").forEach((line) => {
// matching "KEY' and 'VAL' in 'KEY=VAL'
// eslint-disable-next-line no-useless-escape
const keyValueArr = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/);
// matched?
if (keyValueArr != null) {
const key = keyValueArr[1];
let value = keyValueArr[2] || "";
// expand newlines in quoted values
const len = value ? value.length : 0;
if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') {
value = value.replace(/\\n/gm, "\n");
}
// remove any surrounding quotes and extra spaces
value = value.replace(/(^['"]|['"]$)/g, "").trim();
res[key] = value;
}
});
return res;
}
// console.log('SERVER_ID',SERVER_ID);
/*
*定义多个服务器账号 及 根据 SERVER_ID 导出当前环境服务器账号
*/
const SERVER_LIST = [
{
id: 1,
name: "测试服务器",
domain: "xxx",
host: "xxx.xxx.xx.xx",
port: 22202,
username: "root",
password: "xxxxxxx",
path: "/www/wwwroot/xxxxxxxxx",
},
];
module.exports = SERVER_LIST[SERVER_ID];