前端工程化中的自动化部署
作者:bilibili
来源:SegmentFault 思否社区
前言
快速部署
准备工作

因此,通过代码实现自动化部署脚本,主要需要实现如下,下面以vue项目来为工程项目来具体讲解:
实现本地代码编译;可直接配置npm run build即可进行相关的打包 实现本地编译的代码压缩 通过ssh连接远程服务器 检查对应的远程部署路径是否存在,不存在需要创建 上传本地的压缩包 解压上传的压缩包 删除上传的压缩包 关闭ssh连接 删除本地的压缩包
具体实现
chalk:格式化输出日志的插件,可以通过配置不同的颜色来显示不同的日志打印。https://www.npmjs.com/package/chalk child_process:nodejs的一个子进程模块,可以用来创建一个子进程,并执行一些任务,可以直接在js里面调用shell命令。http://nodejs.cn/api/child_process.html jszip:一个轻量级的zip压缩库,用于压缩编译后的脚本。https://stuk.github.io/jszip/ ssh2:用于通过ssh来连接远程服务器的插件。https://github.com/mscdex/ssh2

基本配置
const config = {// 开发环境dev: {host: '',username: 'root',password: '',catalog: '', // 前端文件压缩目录port: 22, // 服务器ssh连接端口号privateKey: null // 私钥,私钥与密码二选一},// 测试环境test: {host: '', // 服务器ip地址或域名username: 'root', // ssh登录用户password: '', // 密码catalog: '', // 前端文件压缩目录port: 22, // 服务器ssh连接端口号privateKey: null // 私钥,私钥与密码二选一},// 线上环境pro: {host: '', // 服务器ip地址或域名username: 'root', // ssh登录用户password: '', // 密码,请勿将此密码上传至git服务器catalog: '', // 前端文件压缩目录port: 22, // 服务器ssh连接端口号privateKey: null // 私钥,私钥与密码二选一}}module.exports = {// publishEnv: pro,publishEnv: config.pro, // 发布环境buildDist: 'dist', // 前端文件打包之后的目录,默认distbuildCommand: 'npm run build', // 打包前端文件的命令readyTimeout: 20000, // ssh连接超时时间deleteFile: true, // 是否删除线上上传的dist压缩包isNeedBuild: true // s是否需要打包}
压缩打包内容
递归读取打包文件 // 读取文件readDir (obj, nowPath) {const files = fs.readdirSync(nowPath) // 读取目录中的所有文件及文件夹(同步操作)files.forEach((fileName, index) => {// 遍历检测目录中的文件// console.log(fileName, index) // 打印当前读取的文件名const fillPath = nowPath + '/' + fileNameconst file = fs.statSync(fillPath) // 获取一个文件的属性if (file.isDirectory()) {// 如果是目录的话,继续查询const dirlist = zip.folder(fileName) // 压缩对象中生成该目录this.readDir(dirlist, fillPath) // 重新检索目录文件} else {obj.file(fileName, fs.readFileSync(fillPath)) // 压缩目录添加文件}})}压缩文件夹下的所有文件// 压缩文件夹下的所有文件zipFile (filePath) {return new Promise((resolve, reject) => {let desc ='*******************************************\n' +'*** 正在压缩 ***\n' +'*******************************************\n'console.log(chalk.blue(desc))this.readDir(zip, filePath)zip.generateAsync({// 设置压缩格式,开始打包type: 'nodebuffer', // nodejs用compression: 'DEFLATE', // 压缩算法compressionOptions: {// 压缩级别level: 9}}).then(content => {fs.writeFileSync(path.join(rootDir, '/', this.fileName),content,'utf-8')desc ='*******************************************\n' +'*** 压缩成功 ***\n' +'*******************************************\n'console.log(chalk.green(desc))resolve({success: true})}).catch(err => {console.log(chalk.red(err))reject(err)})})}使用child_process的exec来运行npm run build脚本打包// 打包本地前端文件buildProject () {return new Promise((resolve, reject) => {exec(Config.buildCommand, async (error, stdout, stderr) => {if (error) {console.error(error)reject(error)} else if (stdout) {resolve({stdout,success: true})} else {console.error(stderr)reject(stderr)}})})}连接ssh服务器通过ssh2的client来创建ssh连接 // 连接服务器connectServer () {return new Promise((resolve, reject) => {const conn = this.connconn.on('ready', () => {resolve({success: true})}).on('error', (err) => {reject(err)}).on('end', () => {const desc ='*******************************************\n' +'*** SSH连接已结束 ***\n' +'*******************************************\n'console.log(chalk.green(desc))}).on('close', () => {const desc ='*******************************************\n' +'*** SSH连接已关闭 ***\n' +'*******************************************\n'console.log(chalk.green(desc))}).connect(this.server)})}上传压缩的工程文件判断上传路径是否存在// 判断文件是否存在,如果不存在则进行创建文件夹await sshCon.execSsh(`if [[ ! -d ${sshConfig.catalog} ]]; thenmkdir -p ${sshConfig.catalog}fi`)通过client的sftp讲本地的压缩包上传到指定的服务器的对应地址 // 上传文件uploadFile ({ localPath, remotePath }) {return new Promise((resolve, reject) => {return this.conn.sftp((err, sftp) => {if (err) {reject(err)} else {sftp.fastPut(localPath, remotePath, (err, result) => {if (err) {reject(err)}resolve({success: true,result})})}})})}解压上传的工程文件通过exec来执行ssh命令的 // 执行ssh命令execSsh (command) {return new Promise((resolve, reject) => {return this.conn.exec(command, (err, stream) => {if (err || !stream) {reject(err)} else {stream.on('close', (code, signal) => {resolve({success: true})}).on('data', function (data) {}).stderr.on('data', function (data) {resolve({success: false,error: data.toString()})})}})})}解压上传的压缩文件desc ='*******************************************\n' +'*** 上传文件成功,开始解压文件 ***\n' +'*******************************************\n'console.log(chalk.green(desc))const zipRes = await sshCon.execSsh(`unzip -o ${sshConfig.catalog + '/' + fileName} -d ${sshConfig.catalog}`).catch((e) => {})if (!zipRes || !zipRes.success) {console.error('----解压文件失败,请手动解压zip文件----')console.error(`----错误原因:${zipRes.error}----`)return false} else if (Config.deleteFile) {desc ='*******************************************\n' +'*** 解压文件成功,开始删除上传的压缩包 ***\n' +'*******************************************\n'console.log(chalk.green(desc))删除上传的工程文件删除对应的压缩包 desc ='*******************************************\n' +'*** 解压文件成功,开始删除上传的压缩包 ***\n' +'*******************************************\n'console.log(chalk.green(desc))// 注意:rm -rf为危险操作,请勿对此段代码做其他非必须更改const deleteZipRes = await sshCon.execSsh(`rm -rf ${sshConfig.catalog + '/' + fileName}`).catch((e) => {})if (!deleteZipRes || !deleteZipRes.success) {console.log(chalk.pink('----删除文件失败,请手动删除zip文件----'))console.log(chalk.red(`----错误原因:${deleteZipRes.error}----`))return false}关闭ssh连接封装关闭的服务器连接 // 结束连接endConn () {this.conn.end()if (this.connAgent) {this.connAgent.end()}}删除本地的压缩包文件封装删除本地的压缩包 // 删除本地文件deleteLocalFile () {return new Promise((resolve, reject) => {fs.unlink(path.join(rootDir, '/', this.fileName), function (error) {if (error) {const desc ='*******************************************\n' +'*** 本地文件删除失败 ***\n' +'*******************************************\n'console.log(chalk.yellow(desc))reject(error)} else {const desc ='*******************************************\n' +'*** 删除成功 ***\n' +'*******************************************\n'console.log(chalk.blue(desc))resolve({success: true})}})})}脚本命令的配置在项目的package.json中配置命令"ssh": "node ./build/ssh.js"完整的实现ssh流程// SSH连接,上传,解压,删除等相关操作async function sshUpload (sshConfig, fileName) {const sshCon = new SSH(sshConfig)const sshRes = await sshCon.connectServer().catch((e) => {console.error(e)})if (!sshRes || !sshRes.success) {const desc ='*******************************************\n' +'*** ssh连接失败 ***\n' +'*******************************************\n'console.log(chalk.red(desc))return false}let desc ='*******************************************\n' +'*** 连接服务器成功,开始上传文件 ***\n' +'*******************************************\n'console.log(chalk.green(desc))// 判断文件是否存在,如果不存在则进行创建文件夹await sshCon.execSsh(`if [[ ! -d ${sshConfig.catalog} ]]; thenmkdir -p ${sshConfig.catalog}fi`)const uploadRes = await sshCon.uploadFile({localPath: path.join(rootDir, '/', fileName),remotePath: sshConfig.catalog + '/' + fileName}).catch((e) => {console.error(e)})if (!uploadRes || !uploadRes.success) {console.error('----上传文件失败,请重新上传----')return false}desc ='*******************************************\n' +'*** 上传文件成功,开始解压文件 ***\n' +'*******************************************\n'console.log(chalk.green(desc))const zipRes = await sshCon.execSsh(`unzip -o ${sshConfig.catalog + '/' + fileName} -d ${sshConfig.catalog}`).catch((e) => {})if (!zipRes || !zipRes.success) {console.error('----解压文件失败,请手动解压zip文件----')console.error(`----错误原因:${zipRes.error}----`)return false} else if (Config.deleteFile) {desc ='*******************************************\n' +'*** 解压文件成功,开始删除上传的压缩包 ***\n' +'*******************************************\n'console.log(chalk.green(desc))// 注意:rm -rf为危险操作,请勿对此段代码做其他非必须更改const deleteZipRes = await sshCon.execSsh(`rm -rf ${sshConfig.catalog + '/' + fileName}`).catch((e) => {})if (!deleteZipRes || !deleteZipRes.success) {console.log(chalk.pink('----删除文件失败,请手动删除zip文件----'))console.log(chalk.red(`----错误原因:${deleteZipRes.error}----`))return false}}// 结束ssh连接sshCon.endConn()return true}实际运行脚本// 执行前端部署;(async () => {const file = new File()let desc ='*******************************************\n' +'*** 开始编译 ***\n' +'*******************************************\n'if (Config.isNeedBuild) {console.log(chalk.green(desc))// 打包文件const buildRes = await file.buildProject().catch((e) => {console.error(e)})if (!buildRes || !buildRes.success) {desc ='*******************************************\n' +'*** 打包出错,请检查错误 ***\n' +'*******************************************\n'console.log(chalk.red(desc))return false}console.log(chalk.blue(buildRes.stdout))desc ='*******************************************\n' +'*** 编译成功 ***\n' +'*******************************************\n'console.log(chalk.green(desc))}// 压缩文件const res = await file.zipFile(path.join(rootDir, '/', Config.buildDist)).catch(() => {})if (!res || !res.success) return falsedesc ='*******************************************\n' +'*** 开始部署 ***\n' +'*******************************************\n'console.log(chalk.green(desc))const bol = await sshUpload(Config.publishEnv, file.fileName)if (bol) {desc ='\n******************************************\n' +'*** 部署成功 ***\n' +'******************************************\n'console.log(chalk.green(desc))file.stopProgress()} else {process.exit(1)}})()完整的ssh.js代码const { exec } = require('child_process')const path = require('path')const JSZIP = require('jszip')const fs = require('fs')const Client = require('ssh2').Clientconst Config = require('./config.js')const chalk = require('chalk')const zip = new JSZIP()// 前端打包文件的目录const rootDir = path.resolve(__dirname, '..')/*** ssh连接*/class SSH {constructor ({ host, port, username, password, privateKey }) {this.server = {host,port,username,password,privateKey}this.conn = new Client()}// 连接服务器connectServer () {return new Promise((resolve, reject) => {const conn = this.connconn.on('ready', () => {resolve({success: true})}).on('error', (err) => {reject(err)}).on('end', () => {const desc ='*******************************************\n' +'*** SSH连接已结束 ***\n' +'*******************************************\n'console.log(chalk.green(desc))}).on('close', () => {const desc ='*******************************************\n' +'*** SSH连接已关闭 ***\n' +'*******************************************\n'console.log(chalk.green(desc))}).connect(this.server)})}// 上传文件uploadFile ({ localPath, remotePath }) {return new Promise((resolve, reject) => {return this.conn.sftp((err, sftp) => {if (err) {reject(err)} else {sftp.fastPut(localPath, remotePath, (err, result) => {if (err) {reject(err)}resolve({success: true,result})})}})})}// 执行ssh命令execSsh (command) {return new Promise((resolve, reject) => {return this.conn.exec(command, (err, stream) => {if (err || !stream) {reject(err)} else {stream.on('close', (code, signal) => {resolve({success: true})}).on('data', function (data) {}).stderr.on('data', function (data) {resolve({success: false,error: data.toString()})})}})})}// 结束连接endConn () {this.conn.end()if (this.connAgent) {this.connAgent.end()}}}/** 本地操作* */class File {constructor () {this.fileName = this.formateName()}// 删除本地文件deleteLocalFile () {return new Promise((resolve, reject) => {fs.unlink(path.join(rootDir, '/', this.fileName), function (error) {if (error) {const desc ='*******************************************\n' +'*** 本地文件删除失败 ***\n' +'*******************************************\n'console.log(chalk.yellow(desc))reject(error)} else {const desc ='*******************************************\n' +'*** 删除成功 ***\n' +'*******************************************\n'console.log(chalk.blue(desc))resolve({success: true})}})})}// 读取文件readDir (obj, nowPath) {const files = fs.readdirSync(nowPath) // 读取目录中的所有文件及文件夹(同步操作)files.forEach((fileName, index) => {// 遍历检测目录中的文件// console.log(fileName, index) // 打印当前读取的文件名const fillPath = nowPath + '/' + fileNameconst file = fs.statSync(fillPath) // 获取一个文件的属性if (file.isDirectory()) {// 如果是目录的话,继续查询const dirlist = zip.folder(fileName) // 压缩对象中生成该目录this.readDir(dirlist, fillPath) // 重新检索目录文件} else {obj.file(fileName, fs.readFileSync(fillPath)) // 压缩目录添加文件}})}// 压缩文件夹下的所有文件zipFile (filePath) {return new Promise((resolve, reject) => {let desc ='*******************************************\n' +'*** 正在压缩 ***\n' +'*******************************************\n'console.log(chalk.blue(desc))this.readDir(zip, filePath)zip.generateAsync({// 设置压缩格式,开始打包type: 'nodebuffer', // nodejs用compression: 'DEFLATE', // 压缩算法compressionOptions: {// 压缩级别level: 9}}).then(content => {fs.writeFileSync(path.join(rootDir, '/', this.fileName),content,'utf-8')desc ='*******************************************\n' +'*** 压缩成功 ***\n' +'*******************************************\n'console.log(chalk.green(desc))resolve({success: true})}).catch(err => {console.log(chalk.red(err))reject(err)})})}// 打包本地前端文件buildProject () {return new Promise((resolve, reject) => {exec(Config.buildCommand, async (error, stdout, stderr) => {if (error) {console.error(error)reject(error)} else if (stdout) {resolve({stdout,success: true})} else {console.error(stderr)reject(stderr)}})})}// 停止程序之前需删除本地压缩包文件stopProgress () {this.deleteLocalFile().catch((e) => {console.log(chalk.red('----删除本地文件失败,请手动删除----'))console.log(chalk.red(e))process.exit(1)}).then(() => {const desc ='*******************************************\n' +'*** 已删除本地压缩包文件 ***\n' +'*******************************************\n'console.log(chalk.green(desc))process.exitCode = 0})}// 格式化命名文件名称formateName () {// 压缩包的名字const date = new Date()const year = date.getFullYear()const month = date.getMonth() + 1const day = date.getDate()const timeStr = `${year}_${month}_${day}`return `${Config.buildDist}-${timeStr}-${Math.random().toString(16).slice(2)}.zip`}}// SSH连接,上传,解压,删除等相关操作async function sshUpload (sshConfig, fileName) {const sshCon = new SSH(sshConfig)const sshRes = await sshCon.connectServer().catch((e) => {console.error(e)})if (!sshRes || !sshRes.success) {const desc ='*******************************************\n' +'*** ssh连接失败 ***\n' +'*******************************************\n'console.log(chalk.red(desc))return false}let desc ='*******************************************\n' +'*** 连接服务器成功,开始上传文件 ***\n' +'*******************************************\n'console.log(chalk.green(desc))// 判断文件是否存在,如果不存在则进行创建文件夹await sshCon.execSsh(`if [[ ! -d ${sshConfig.catalog} ]]; thenmkdir -p ${sshConfig.catalog}fi`)const uploadRes = await sshCon.uploadFile({localPath: path.join(rootDir, '/', fileName),remotePath: sshConfig.catalog + '/' + fileName}).catch((e) => {console.error(e)})if (!uploadRes || !uploadRes.success) {console.error('----上传文件失败,请重新上传----')return false}desc ='*******************************************\n' +'*** 上传文件成功,开始解压文件 ***\n' +'*******************************************\n'console.log(chalk.green(desc))const zipRes = await sshCon.execSsh(`unzip -o ${sshConfig.catalog + '/' + fileName} -d ${sshConfig.catalog}`).catch((e) => {})if (!zipRes || !zipRes.success) {console.error('----解压文件失败,请手动解压zip文件----')console.error(`----错误原因:${zipRes.error}----`)return false} else if (Config.deleteFile) {desc ='*******************************************\n' +'*** 解压文件成功,开始删除上传的压缩包 ***\n' +'*******************************************\n'console.log(chalk.green(desc))// 注意:rm -rf为危险操作,请勿对此段代码做其他非必须更改const deleteZipRes = await sshCon.execSsh(`rm -rf ${sshConfig.catalog + '/' + fileName}`).catch((e) => {})if (!deleteZipRes || !deleteZipRes.success) {console.log(chalk.pink('----删除文件失败,请手动删除zip文件----'))console.log(chalk.red(`----错误原因:${deleteZipRes.error}----`))return false}}// 结束ssh连接sshCon.endConn()return true}// 执行前端部署;(async () => {const file = new File()let desc ='*******************************************\n' +'*** 开始编译 ***\n' +'*******************************************\n'if (Config.isNeedBuild) {console.log(chalk.green(desc))// 打包文件const buildRes = await file.buildProject().catch((e) => {console.error(e)})if (!buildRes || !buildRes.success) {desc ='*******************************************\n' +'*** 打包出错,请检查错误 ***\n' +'*******************************************\n'console.log(chalk.red(desc))return false}console.log(chalk.blue(buildRes.stdout))desc ='*******************************************\n' +'*** 编译成功 ***\n' +'*******************************************\n'console.log(chalk.green(desc))}// 压缩文件const res = await file.zipFile(path.join(rootDir, '/', Config.buildDist)).catch(() => {})if (!res || !res.success) return falsedesc ='*******************************************\n' +'*** 开始部署 ***\n' +'*******************************************\n'console.log(chalk.green(desc))const bol = await sshUpload(Config.publishEnv, file.fileName)if (bol) {desc ='\n******************************************\n' +'*** 部署成功 ***\n' +'******************************************\n'console.log(chalk.green(desc))file.stopProgress()} else {process.exit(1)}})()

评论
