在前端工程化中,前端开发人员终于在不断的提升本身的地位,不再是简单的切图仔了。固然,随之而来的就是咱们的工做内容变得愈来愈多,变得愈来愈繁琐。不只要不断的学习新的前端技术内容,并且还要独立维护前端的部署工做。所以,如何能快速的进行工程化内容的部署,就是一件很是有价值的事情。html
对于前端的部署来讲,其实主要就是将编译后的工程化项目(以vue来讲就是将npm run build的dist文件夹)直接部署到对应的服务器的指定目录下便可,其余的内容咱们暂时不在此处作过多的讲解。前端
所以,目前通常会使用SFTP工具(如:FileZilla:www.filezilla.cn/,Cyberduck:cyberduck.io/)来上传构建好的前端代码到服务器。这种方式虽然也是比较快的,可是每次要本身进行打包编译=》压缩=》打开对应的工具=》找到对应的路径,手动的将相关的文件上传到对应的服务中。而且为了部署到不一样的环境中(通常项目开发包括:dev开发环境、test测试环境、uat测试环境、pro测试环境等)还要重复的进行屡次的重复性操做。这种方式不只繁琐,并且还下降了咱们程序员的身份。因此咱们须要用自动化部署来代替手动 ,这样一方面能够提升部署效率,另外一方面开发人员能够少作一些他们觉得的无用功。vue
话很少说,说干就干。首先,咱们先梳理一下通常的部署流程,主要是先将本地的工程化代码进行打包编译=>经过ssh登陆到服务器=>将本地编译的代码上传到服务器指定的路径中,具体流程以下: 所以,经过代码实现自动化部署脚本,主要须要实现以下,下面以vue项目来为工程项目来具体讲解:node
3.经过ssh链接远程服务器 3. 检查对应的远程部署路径是否存在,不存在须要建立 4. 上传本地的压缩包 5. 解压上传的压缩包 6. 删除上传的压缩包 7. 关闭ssh链接 8. 删除本地的压缩包git
为了在可以实现以上的几个步骤,咱们须要引入一些依赖包,以此来进行相关步骤的操做和日志的打印输出程序员
大体流程以下: github
为了可以将部署相关的内容,如服务器信息,部署的路径等内容进行统一的管理,以便进行将来的可视化配置。所以,在项目中建立一个独立的文件夹,统一管理部署相关的文件,而且创建一个config.js和ssh.js文件,分别用于配置相关的部署信息和具体的部署脚本。其中,config.js中的配置具体以下:算法
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', // 前端文件打包以后的目录,默认dist
buildCommand: 'npm run build', // 打包前端文件的命令
readyTimeout: 20000, // ssh链接超时时间
deleteFile: true, // 是否删除线上上传的dist压缩包
isNeedBuild: true // s是否须要打包
}
复制代码
压缩打包的内容,使用JSZIP插件,初始化一个const zip = new JSZIP(),而后在按照对应的语法进行具体的实现,其实现过程主要是经过的先递归读取相关的文件,而后加入到zip对象中,最后经过插件进行具体的压缩,最后写入到磁盘中。具体代码以下: 递归读取打包文件shell
// 读取文件
readDir (obj, nowPath) {
const files = fs.readdirSync(nowPath) // 读取目录中的全部文件及文件夹(同步操做)
files.forEach((fileName, index) => {
// 遍历检测目录中的文件
// console.log(fileName, index) // 打印当前读取的文件名
const fillPath = nowPath + '/' + fileName
const file = fs.statSync(fillPath) // 获取一个文件的属性
if (file.isDirectory()) {
// 若是是目录的话,继续查询
const dirlist = zip.folder(fileName) // 压缩对象中生成该目录
this.readDir(dirlist, fillPath) // 从新检索目录文件
} else {
obj.file(fileName, fs.readFileSync(fillPath)) // 压缩目录添加文件
}
})
}
复制代码
压缩文件夹下的全部文件npm
// 压缩文件夹下的全部文件
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)
}
})
})
}
复制代码
经过ssh2的client来建立ssh链接
// 链接服务器
connectServer () {
return new Promise((resolve, reject) => {
const conn = this.conn
conn
.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} ]]; then
mkdir -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
}
复制代码
封装关闭的服务器链接
// 结束链接
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链接,上传,解压,删除等相关操做
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} ]]; then
mkdir -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 false
desc =
'*******************************************\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)
}
})()
复制代码
const { exec } = require('child_process')
const path = require('path')
const JSZIP = require('jszip')
const fs = require('fs')
const Client = require('ssh2').Client
const 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.conn
conn
.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 + '/' + fileName
const 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() + 1
const 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} ]]; then
mkdir -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 false
desc =
'*******************************************\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)
}
})()
复制代码