今天看啥  ›  专栏  ›  晨萧辰

基于node实现Vue打包部署脚本

晨萧辰  · 掘金  ·  · 2020-03-20 10:51
阅读 79

基于node实现Vue打包部署脚本

偶然看到一篇文章叫抛弃jenkins,拥抱node。虽然没什么兴趣点进去看,但也给了我启示,抽空写了一个自动部署脚本

本文使用到的node指令生成在之前文章有写到,感兴趣的可以跳转过去:juejin.im/post/5dcbb4…

使用技术栈

  • ssh2 (使用ssh登录服务器)
  • fs (文件处理)
  • compress (压缩脚本)

思维图

代码压缩

 compressing.zip
 .compressDir('./dist/.', './dist.zip')
 .then(() => {
     console.log(`Tip: 文件压缩成功`);
     conFun()
 })
 .catch(err => {
     console.log("Tip: 压缩报错");
     console.error(err);
 });

复制代码

使用函数: compressing.zip.compressDir(source, dest, opts)

注!!! source文件路径为:'./dist/.',效果为解压出的文件没有dist目录,如果需要dist文件目录则改成‘./dist’

连接函数

const params = {file: `./dist.zip`, target: `${servicePath}/dist.zip`}
// 连接函数
function conFun(){
  console.log('开始连接...');
  
  connection = new ssh2();
  connection.connect({
      "host": ip ,
      "username": user,
      "password": password
  });
  connection.on('error', function (err) {
      connection.end()
      console.log('连接失败');
  });
  connection.on('ready', function () {
      upLoadFile(connection, params)
  });
}

// 上传函数
function upLoadFile(conn, params) {
    const file = params.file  
    const target = params.target
    if (!conn) {
        return
    }
    conn.sftp(function (err, sftp) {
        if (err) {
            throw err
        }
        sftp.fastPut(file, target, {}, function (err, result) {
            if (err) {
                throw err
            }
            // 执行linux命令
            Shell(conn)
        })
    })
}
复制代码

params{file: localPath, target: servicePath}, file存放本地dist压缩文件,target为服务器部署地 址

执行脚本函数

// 执行脚本函数
const comment = [
  `cd ${servicePath}`,
  'unzip -o dist.zip',
  'rm -f dist.zip',  
  'exit',
  'close'
]

function Shell(conn) {
    conn.shell(function (err, stream) {
        if (err) throw err;
        stream.on('close', function () {
          console.log('发布完成!!');
          // 删除压缩包
          fs.unlinkSync('./dist.zip')
          conn.end();
        }).on('data', function (data) {
          console.log('STDOUT: ' + data)
        });
        stream.end(comment.join('\n'));
    });
    
}
复制代码

在服务器上解压dist压缩包,随后删除压缩包。

打包后执行上传脚本

在安装完node指令后,只需在vue的打包指令后加上打包指令即可

这样我们只需要在npm run build完成打包后自动将代码上传到指定服务器,完成自动部署。

完善

当项目较多需要多个部署环境,可以通过定义环境变量决定部署环境。

代码:github.com/justworkhar…




原文地址:访问原文地址
快照地址: 访问文章快照