前端实现打包后自动上传代码到服务器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、编写相关代码constpathrequire(path);constfsrequire(fs);constClientrequire(ssh2-sftp-client);constorarequire(ora);letspinnernullconstconfig{host:,// 服务器地址port:22,username:root,// 服务器账号要有生产项目发布的权限password:// 密码};lettotalFileCount0letnum0functionfoldFileCount(folderPath){letcount0;constfilesfs.readdirSync(folderPath);for(constfileoffiles){constfilePathpath.join(folderPath,file);conststatsfs.statSync(filePath);if(stats.isFile()){countcount1}elseif(stats.isDirectory()){countcountfoldFileCount(filePath);}}returncount;}asyncfunctionuploadFilesToRemote(localFolderPath,remoteFolderPath,sftp){constfilesfs.readdirSync(localFolderPath);for(constfileoffiles){letlocalFilePathpath.join(localFolderPath,file)letremoteFilePathpath.join(remoteFolderPath,file)remoteFilePathremoteFilePath.replace(/\\/g,/)conststatsfs.statSync(localFilePath)if(stats.isFile()){awaitsftp.put(localFilePath,remoteFilePath)numnum1letprogress((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;// 服务器项目文件夹totalFileCountfoldFileCount(localFolderPath)if(!totalFileCount)returnconstsftpnewClient()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文件夹成功);spinnerora(自动化脚本执行开始).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控制台输出打开测试环境页面刷新页面内容已经是最新的测试通过。