前端实现打包后自动上传代码到服务器

前端实现打包后自动上传代码到服务器

前端实现打包后自动上传代码到服务器

  • 1、背景
  • 1、安装依赖
  • 2、代码实现
        • 1、创建built.js文件,和package平级
        • 2、编写相关代码
        • 3、完善打包命令
        • 4、结果

1、背景

由于公司没有成熟的CI/CD流程,每次发布测试环境都要打开xftp,连接账号密码,公司电脑有比较卡,打开xftp都要反应半天,今天我实在是受不了了,于是就写了个脚本。

1、安装依赖

npm install ora-Dnpm install ssh2-sftp-client-D

因为只在开发阶段使用,所以只添加开发依赖

2、代码实现

1、创建built.js文件,和package平级
2、编写相关代码
constpath=require('path');constfs=require('fs');constClient=require('ssh2-sftp-client');constora=require('ora');letspinner=nullconstconfig={host:'',// 服务器地址port:'22',username:'root',// 服务器账号,要有生产项目发布的权限password:''// 密码};lettotalFileCount=0letnum=0functionfoldFileCount(folderPath){letcount=0;constfiles=fs.readdirSync(folderPath);for(constfileoffiles){constfilePath=path.join(folderPath,file);conststats=fs.statSync(filePath);if(stats.isFile()){count=count+1}elseif(stats.isDirectory()){count=count+foldFileCount(filePath);}}returncount;}asyncfunctionuploadFilesToRemote(localFolderPath,remoteFolderPath,sftp){constfiles=fs.readdirSync(localFolderPath);for(constfileoffiles){letlocalFilePath=path.join(localFolderPath,file)letremoteFilePath=path.join(remoteFolderPath,file)remoteFilePath=remoteFilePath.replace(/\\/g,'/')conststats=fs.statSync(localFilePath)if(stats.isFile()){awaitsftp.put(localFilePath,remoteFilePath)num=num+1letprogress=((num/totalFileCount)*100).toFixed(2)+'%'spinner.text='当前上传进度为:'+progress}elseif(stats.isDirectory()){awaitsftp.mkdir(remoteFilePath,true)awaituploadFilesToRemote(localFilePath,remoteFilePath,sftp)}}}asyncfunctionmain(){constlocalFolderPath='./dist';// 本地打包产物文件夹constremoteFolderPath='/opt/www/dist';// 服务器项目文件夹totalFileCount=foldFileCount(localFolderPath)if(!totalFileCount)returnconstsftp=newClient()try{console.log('连接服务器');awaitsftp.connect(config);console.log('服务器连接成功');console.log('删除旧的dist文件夹');awaitsftp.rmdir(remoteFolderPath,true)console.log('删除旧的dist文件夹成功');console.log('新建新的dist文件夹');awaitsftp.mkdir(remoteFolderPath,true)console.log('新建新的dist文件夹成功');spinner=ora('自动化脚本执行开始').start()awaituploadFilesToRemote(localFolderPath,remoteFolderPath,sftp)}catch(err){console.log("出现错误")console.log(err);}finally{sftp.end();spinner.info('自动化脚本执行结束')}}main();
3、完善打包命令

改造原有打包命令,添加 && node ./built-dev.js ,这样打包完成后会自动执行测试环境发布任务,再也不会忘记发版,等测试测的时候,找出来几个bug,最后发现是测试环境没法发布最新代码。

"build:dev":"dotenv -e .env.development node scripts/build.js && node ./built-dev.js",
4、结果

执行命令

npm run build:dev

控制台输出

打开测试环境页面,刷新页面,内容已经是最新的,测试通过。