前端资源部署发布

159 阅读1分钟

1.添加依赖

pnpm add -D ssh2-sftp-client
或
npm i -D ssh2-sftp-client
...

2.引入ssh文件推送插件编写脚本

// 示例文件路径 publish/index.js

// 文件推送依赖
import Client from 'ssh2-sftp-client'
// 配置自己服务器信息
const hostConfig = {
  host: 'ip',
  port: 22,
  username: 'root',
  password: 'password'
}
// 配置要发布推送的文件夹路径、要覆盖的文件
const filesConfig = {
  localPath: './dist', // 要上传的文件夹路径
  remotePath: '/env/nginx/html/dist' // 要覆盖的远程服务器文件夹(dist会被删除)
}
// 创建服务
const client = new Client();
/** 执行脚本主函数 */
const main = async (config, localPath, remotePath) => {
  const startLog = new Log('代码远程部署中...')
  try {
    await client.connect(config);
    startLog.end('服务器连接已创建!')
    if (await client.exists(remotePath)) {
      const delLog = new Log('删除旧文件中...')
      const res = await client.rmdir(remotePath, true)
      delLog.end(`删除成功: ${res}`)
    }
    const upLog = new Log('文件上传中...')
    const rslt = await client.uploadDir(localPath, remotePath);
    upLog.end(`上传成功: ${rslt}`)
    console.log('部署成功!');
    client.end();
    return rslt;
  } catch (err) {
    startLog.end(`失败: ${err}`)
    client.end();
  }
}
/** 日志输入函数 */
class Log {
  constructor (text) {
    this.stdout = process.stdout
    this.stdout.write(`${text}`)
  }

  up (text) {
    this.clearLine()
    this.stdout.write(`\r${text} `)
  }

  end (text) {
    this.clearLine()
    this.stdout.write(`\r${text}\n`)
  }

  clearLine () {
    this.stdout.clearLine()
    this.stdout.cursorTo(0)
  }
}
// 执行
main(hostConfig, filesConfig.localPath, filesConfig.remotePath);

3.配置scripts publish命令

"scripts": {
    "dev": "vite",
    "mock": "vite --mode mock",
    "build": "rm -rf ./dist && vite build",
    "publish": "pnpm run build && node ./publish",
}

4.执行发布

pnpm run publish

总结

再也不需要登录服务器执行一堆操作啦!

想要执行更多的任务可自行添加呦!