当前位置: 首页 > 工具软件 > ShellJS > 使用案例 >

vue项目Shelljs一键打包自动部署

公羊曜灿
2023-12-01

首先安装shelljs和ssh2-sftp-client

cnpm i shelljs ssh2-sftp-client --save-dev

Shelljs是Node.js下的脚本语言解析器,具有丰富且强大的底层操作(Windows/Linux/OS X)权限

ssh2-sftp-client是一个用于node.js的SFTP客户端,一个用于SSH2的包装程序(提供高级便利抽象)以及一个基于Promise的API

package.json里面新增命令 创建文件

...
	"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "upload": "node upload/index.js"
  },
...

建upload文件夹 里面新建config.js和index.js文件

config.js

    module.exports = {
      ip: "", // ssh地址
      username: "", // ssh 用户名
      port:"",      //端口
      password: "", // ssh 密码
      path: '/opt/html/', // 操作开始文件夹 可以直接指向配置好的地址
      rmpath: '/opt/html' // 需要删除的文件夹
    }
  
index.js
        const config = require('./config.js')
    const shell = require('shelljs')
    const path = require('path');
    let Client = require('ssh2-sftp-client');
    // 打包 npm run build
    const compileDist = async () => {
      if(shell.exec(`npm run build`).code==0) {//判断是否打包完成
        console.log("打包成功")
      }
    }
    
    async function connectSSh() {
      let sftp = new Client();
      sftp.connect({
        host: config.ip, // 服务器 IP
        port: config.port,
        username: config.username,
        password: config.password
      }).then(() => {
        console.log("先执行删除服务器文件")
        return sftp.rmdir(config.rmpath, true);
      }).then(() => {
        // 上传文件
        console.log("开始上传")
        return sftp.uploadDir(path.resolve(__dirname, '../dist'), config.path);
      }).then((data) => {
        console.log("上传完成");
        sftp.end();
      }).catch((err) => {
        console.log(err, '失败');
        sftp.end();
      });
    }
    async function runTask() {
      await compileDist()     //打包完成
      await connectSSh()      //提交上传
    }
    runTask()
 类似资料: