前端scp2自动打包部署

1. npm安装 scp2, ora(建议此版本^5.1.0,版本过高会报错), cross-env(已存在就不需要安装)
2. package.json新增发布代码命令
  "scripts": {
    "deploy": "vite build && cross-env NODE_ENV=production node ./deploy",
    // --mode test(为vue .env对用的环境)   cross-env NODE_ENV=test(打包部署时文件上传的环境)
    "deploy:test": "vite build --mode test && cross-env NODE_ENV=test node ./deploy",
  },
3.新建根目录新建deploy.js
const scpClient = require("scp2");
const ora = require("ora");
const chalk = require("chalk");
const spinner = ora("正在发布到服务器...");

const Client = require("ssh2").Client;
const conn = new Client();

// 默认测试环境代码地址
let path = "";


if (process.env.NODE_ENV == "test") {
    path = "/mnt/www/ysss/ysss-merchant-admin-ui/test";
    console.log("测试环境打包完成");
}
// 上传代码到正式环境
if (process.env.NODE_ENV == "production") {
    path = "mnt/www/ysss/ysss-merchant-admin-ui/prod";
    console.log("正式环境打包完成");
}

const server = {
    host: "", // 服务器的IP地址
    port: "22", // 服务器端口
    username: "root", // 用户名
    password: "", // 密码
    path: path, // 项目部署的服务器目标位置
    command: "",
    // 若需要删除服务器文件可使用下面代码
    // command: 'rm -rf /mnt/www/ysss/ysss-merchant-admin-ui/test/*' // 删除命令
};

if (path) {
    uploadFile();
}
function uploadFile() {
    conn.on("ready", () => {
        conn.exec(server.command, (err, stream) => {
            if (err) {
                throw err;
            }
            stream.on("close", () => {
                spinner.start();
                scpClient.scp(
                    "./dist/", // 本地项目打包文件的位置
                    {
                        host: server.host,
                        port: server.port,
                        username: server.username,
                        password: server.password,
                        path: server.path,
                    },
                    (err) => {
                        spinner.stop();
                        if (err) {
                            console.log(chalk.red("发布失败!"));
                            throw err;
                        } else {
                            console.log(chalk.green("项目发布成功!"));
                        }
                    }
                );
                conn.end();
            }).on("data", (data) => {
                console.log("STDOUT: " + data);
            }).stderr.on("data", (data) => {
                console.log("STDERR: " + data);
            });
        });
    }).connect({
        host: server.host,
        port: server.port,
        username: server.username,
        password: server.password,
    });
}
4.终端执行yarn deploy:test(或 node deploy:test)即可打包发布到服务器

你可能感兴趣的:(前端scp2自动打包部署)