用Python写一个简单的一键打包部署vue前端项目脚本

最近工作上需要多次修改和部署前端项目到不同测试环境,而且近几周优化上线的次数比较多。本着能一步完成的事儿就绝不做第二步的原则,我东拼西凑写了个一键修改配置、打包vue项目并部署至指定环境的脚本,每一个步骤已经经过验证,目前还没遇到问题。在此分享一下,话不多说,上代码。

import os
import time
import paramiko
import shutil

vue_prj_path = 'E:\\vue_prj'
port = 22
target_dir = '/usr/local/nginx/html/'
old = ['1xx.xxx.xx.xx:8088']
file_names = ['vue.config.js',
              'customizeEnv.js']
# sit
new = '1xx.xx.xx.xx:8088'
hostnames = ['1xx.2.1.1']
username = 'root'
password = '<PASSWORD>'
# uat
# new = '1xx.xx.xx.xx:8088'
# hostnames = ['1xx.2.1.1']
# username = 'root'
# password = '<PASSWORD>'
# 测试
# new = '1xx.xx.xx.xx:8088'
# hostnames = ['1xx.2.1.1']
# username = 'root'
# password = '<PASSWORD>'
# 生产
# new = '1xx.xx.xx.xx:8088'
# hostnames = []
# username = ''
# password = ''


def replace_str(file_names, old, new):
    for file_name in file_names:
        file_path = os.path.join(vue_prj_path, file_name)
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            for str in old:
                if str in content:
                    with open(file_path, 'w', encoding='utf-8') as f:
                        content = content.replace(str, new)
                        f.write(content)
                        f.close()
                        break
            print(f'{file_name}已替换指定文本')
        except Exception as e:
            print(f'发生异常:{e}')


def vue_package():
    # 进入项目目录
    os.chdir(vue_prj_path)
    # 替换相关配置文件中的ip
    replace_str(file_names, old, new)
    # 打包前端代码
    os.system('npm run build')
    # 压缩dist
    shutil.make_archive('dist', 'zip', root_dir=vue_prj_path, base_dir='dist')
    # 生产环境的包可以移动到生产打包文件夹,不用上传服务器,金融行业也上传不了
    if new == '1xx.xx.xx.xx:8088':
        print('生产环境的包可以移动到生产打包文件夹,不用上传服务器'.center(100, '='))
        shutil.move('dist.zip', 'E:\\生产发包')
    else:
        # 连接服务器
        for hostname in hostnames:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(hostname=hostname, port=port, username=username, password=password)
            # 删除已存在的备份dist
            print('删除dist_old'.center(100, '='))
            shell = ssh.invoke_shell()
            shell.send(f'cd {target_dir}\n')
            shell.send('rm -rf dist_old\n')
            time.sleep(3)
            while not shell.recv_ready():
                pass
            output = shell.recv(1024).decode('utf-8')
            if 'error' in output.lower():
                print('删除失败!')
            else:
                print('删除成功!')
            # 备份dist
            print('备份dist'.center(100, '='))
            shell.send('mv dist dist_old\n')
            time.sleep(2)
            while not shell.recv_ready():
                pass
            output = shell.recv(1024).decode('utf-8')
            if 'error' in output.lower():
                print('备份失败!')
            else:
                print('备份成功!')
            # 上传dist.zip
            print('上传dist.zip'.center(100, '='))
            sftp = ssh.open_sftp()
            sftp.put('dist.zip', target_dir + 'dist.zip')
            print('解压dist.zip'.center(100, '='))
            shell.send('unzip dist.zip\n')
            time.sleep(2)
            while not shell.recv_ready():
                pass
            output = shell.recv(1024).decode('utf-8')
            if 'error' in output.lower():
                print('解压失败!')
            else:
                print('解压成功!')
            # 关闭相关连接
            sftp.close()
            ssh.close()
        os.remove('dist.zip')
    # 删除本地的dist文件夹和zip
    shutil.rmtree('dist')


if __name__ == '__main__':
    vue_package()

以上代码应该只有paramiko需要特别安装一下,其他的应该都是Python自带的库,所以对离线环境还算是比较友好。

因为我们的项目有比较多的配置后端请求地址的地方需要同步修改(我也不知道为啥领导不允许统一配置文件),所以我专门写了个替换ip地址的方法。剩下的就按部就班执行打包,压缩,移动,上传,解压缩就完事儿了。可以支持多个服务器一起部署,且针对不同的环境有多套配置。整体执行时间,因为我们的项目源代码算是量比较大,且很复杂。大概需要三四分钟,省略了手动打包,上传、解压的操作。一定程度上解放了我自己的部分工作时间。

当然,这个脚本也就是我自己用着顺手就行,所以并没有对执行效率和代码冗余的问题做优化。我也只是一个初学Python的菜鸟,能做到这些我已经有比较大的成就感了!欢迎各位对Python感兴趣的小伙伴一起交流!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值