前端项目中创建自动化部署脚本,用于 Jenkins 触发 npm run publish 来完成远程部署

核心步骤包括:

  1. 读取 server.config.json 配置,获取目标服务器信息
  2. 使用 scp 上传前端打包文件serverWebPath
  3. 使用 ssh 远程执行部署命令 (例如 pm2 restartnginx reload

1. 安装依赖

使用 Node.js 编写 deploy.js 脚本,需要用到 ssh2fs

npm install ssh2 fs-extra dotenv

2. 在config下配置server.config.json文件

javascript 复制代码
{
  "deploy": {
    "host": "10.2...",
    "port": 36000,
    "username": "root",
    "password": "*#00000",
    "serverWebPath": "/...",
    "splitIncludes": ["models"],
    "splitUpload": false
  },
  "sandbox": {
    "host": "10.2...",
    "port": 36000,
    "username": "root",
    "password": "*#00000",
    "serverWebPath": "/...",
    "splitIncludes": [],
    "splitUpload": true
  }
}

3. deploy.js 自动化脚本

项目根目录 创建 scripts/deploy.js,用于 自动化部署

javascript 复制代码
const fs = require("fs-extra");
const path = require("path");
const { Client } = require("ssh2");

// 读取 server.config.json
const configPath = path.resolve(__dirname, "../server.config.json");
const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));

// 选择环境(deploy 或 sandbox)
const env = process.env.ENV || "deploy";
const serverConfig = config[env];

if (!serverConfig) {
  console.error(`配置错误: 未找到环境 ${env} 的配置信息`);
  process.exit(1);
}

// 获取配置信息
const { host, port, username, password, serverWebPath } = serverConfig;
const localBuildPath = path.resolve(__dirname, "../dist"); // 前端打包目录

// 部署逻辑
async function deploy() {
  console.log(`开始部署到 ${env} 环境: ${host}:${port}`);

  const conn = new Client();
  conn
    .on("ready", () => {
      console.log(`连接成功: ${host}`);

      // 上传文件
      uploadFiles(conn)
        .then(() => executeRemoteCommand(conn, `cd ${serverWebPath} && ls -la`))
        .then(() => {
          console.log("部署完成!");
          conn.end();
        })
        .catch((err) => {
          console.error(`部署失败: ${err.message}`);
          conn.end();
        });
    })
    .connect({ host, port, username, password });
}

// 远程执行命令
function executeRemoteCommand(conn, command) {
  return new Promise((resolve, reject) => {
    conn.exec(command, (err, stream) => {
      if (err) return reject(err);
      stream
        .on("close", (code, signal) => resolve(code))
        .on("data", (data) => console.log(`远程输出: ${data.toString()}`))
        .stderr.on("data", (data) => console.error(` 错误: ${data.toString()}`));
    });
  });
}

// 上传文件
function uploadFiles(conn) {
  return new Promise((resolve, reject) => {
    conn.sftp((err, sftp) => {
      if (err) return reject(err);
      sftp.mkdir(serverWebPath, (err) => {
        if (err && err.code !== 4) return reject(err); // 目录已存在则忽略错误
        sftp.fastPut(
          path.join(localBuildPath, "index.html"),
          `${serverWebPath}/index.html`,
          (err) => (err ? reject(err) : resolve())
        );
      });
    });
  });
}

// 执行部署
deploy();

4. 在 package.json 添加 publish 命令

javascript 复制代码
"scripts": {
  "build": "vite build",
  "publish": "npm run build && node scripts/deploy.js"
}
相关推荐
雮尘12 分钟前
LangGraph 与 LangSmith 入门教程(JS/TS 版)
前端·人工智能·langchain
英勇无比的消炎药13 分钟前
新手必看玩转TinyRobot一定要避开这些坑
前端·vue.js
持敬chijing18 分钟前
Web渗透之前后端漏洞-文件上传漏洞-过滤绕过与配置文件漏洞-条件竞争漏洞
前端·安全·web安全·网络安全·网络攻击模型·安全威胁分析
ShGamu21 分钟前
自动化输送设备公司选型参考与核心维度梳理
运维·自动化·自动化输送设备
尼斯湖皮皮怪23 分钟前
iceCoder:验收门控深度分析
前端·agent
周庆猛26 分钟前
Babylon.js 多灯场景在 Windows 上报错:VERTEX shader uniform block count exceeds GL_MAX_VE
前端·数据可视化
胡志辉26 分钟前
深入浅出理解浏览器事件循环:从一道输出题讲到 Chrome 源码
前端·javascript·面试
一晌小贪欢27 分钟前
第26节:自动化办公——利用 Python 自动生成动态分析报告 (PPT/PDF)
开发语言·python·数据分析·自动化·powerpoint·pandas·数据可视化
槑有老呆32 分钟前
用 Bun 写一个 RESTful TodoList,顺便把面向接口编程整明白
前端
英勇无比的消炎药32 分钟前
别再盲目混用AI组件库和传统组件库差距原来这么大
前端·vue.js