前言
需求背景是(相信无论是做vue
或react
项目的童鞋都不会陌生):需要将前端build
之后的dist
文件夹,部署至指定的服务器上,如何编写自动工具,实现自动化一键部署呢?
正文
编写插件
在项目内的src
目录下新增plugins
目录,在该目录内新增deploymentProject.js
文件,内容如下所示:
const fs = require('fs')
const path = require('path')
const axios = require('axios')
const AdmZip = require('adm-zip')
const moment = require('moment')
const FormData = require('form-data')
const zip = new AdmZip()
function delDir(path) {
let files = []
if (fs.existsSync(path)) {
files = fs.readdirSync(path)
files.forEach((file, index) => {
let curPath = path + '/' + file
if (fs.statSync(curPath).isDirectory()) {
delDir(curPath) //递归删除文件夹
} else {
fs.unlinkSync(curPath) //删除文件
}
})
fs.rmdirSync(path)
}
}
module.exports = class DeploymentProjectWebpackPlugin {
constructor(ip) {
this.ip = ip
}
apply(compiler) {
compiler.hooks.afterEmit.tapAsync(
'DeploymentProjectWebpackPlugin',
(compilation, cb) => {
try {
const dist = path.join(__dirname, '../../dist/')
if (fs.existsSync(dist)) {
zip.addLocalFolder(dist)
// const willSendthis = zip.toBuffer()
const zipName = path.join(
__dirname,
'../../dist/' + moment().format('YYYYMMDDHHmm') + '.zip'
)
// or write everything to disk
zip.writeZip(/*target file name*/ zipName, () => {
const formData = new FormData()
formData.append('file', fs.createReadStream(zipName))
formData.append('company', '2dmap')
axios({
url: `http://${this.ip}:3000/system/deployment`,
method: 'post',
data: formData,
headers: formData.getHeaders(),
maxContentLength: Infinity,
maxBodyLength: Infinity,
})
.then((v) => {
console.log('上传完成')
setTimeout(() => {
console.log('开始删除dist目录')
delDir(path.join(__dirname, '../../dist'))
console.log('删除完成dist目录')
}, 2000)
console.log(v)
})
.catch((err) => {
console.log('error:' + err)
})
})
}
} catch (e) {
console.error(e)
} finally {
cb()
}
}
)
}
}
上面代码用到的知识点如下所示:
- 使用
adm-zip
,创建zip
对象,调用addLocalFolder
添加需要被压缩的dist
文件夹,zipName
为压缩后的.zip
文件名称 zip
对象调用writeZip
方法,在回调函数内,调用接口system/deployment
接口,将已被压缩的zipName
内容(回调函数内,dist
文件内容已被压缩,此时可获取到压缩后的内容)以formData
形式,传至服务端,上传完成后,删除之前自动生成的dist
文件夹即可
如何使用插件
在vue.config.js
内增添如下代码:
const DeploymentProjectPlugin = require('./src/plugins/deploymentProject')
module.exports = {
configureWebpack: {
plugins: [
new DeploymentProjectPlugin('10.x.x.x')
]
}
}