使用场景:适用于靠丢压缩包发版的项目,可以实现自动删除原压缩包并且打包成功后自动压缩现有文件,生成新的压缩包。
适用于旧版webpack(如3.0)
首先在build文件夹下新建一个filezip.js文件
const fs = require('fs')
const path = require('path')
const compressing = require('compressing');
class Zip {
constructor(option) {
this.option = option
}
removeDir(dir) {
let files = fs.readdirSync(dir)
for (var i = 0; i < files.length; i++) {
let newPath = path.join(dir, files[i]);
let stat = fs.statSync(newPath)
if (stat.isDirectory()) {
//如果是文件夹就递归下去
this.removeDir(newPath);
} else {
//删除文件
fs.unlinkSync(newPath);
}
}
fs.rmdirSync(dir)//如果文件夹是空的,就将自己删除掉
}
apply(compiler) {
compiler.plugin('done', (compilation) => {
//复制文件的逻辑,此时文件已经编译完成
let exist = fs.existsSync(this.option.filePath)
if (exist) {
if (fs.existsSync(this.option.zipPath + '/chart')) {
//如果chart文件夹存在,先删除,方便后面创建移动操作
this.removeDir(this.option.zipPath + '/chart')
}
fs.mkdirSync(this.option.zipPath + '/chart')
let fileName = "target.zip"
if (this.option.zipName) {
fileName = `/${this.option.zipName}.zip`
}
let zipPath = this.option.zipPath + fileName
if (fs.existsSync(zipPath)) {
// 压缩包存在,先删除压缩包
fs.unlinkSync(zipPath)
}
fs.rename(path.resolve(__dirname, "../dist/static"), path.resolve(__dirname, "../dist/chart/static"), (err) => {
if (err) {
console.log(err, 'static文件夹移动失败')
return
}
})
fs.rename(path.resolve(__dirname, "../dist/index.html"), path.resolve(__dirname, "../dist/chart/index.html"), (err) => {
if (err) {
console.log(err, 'index.html文件移动失败')
return
}
})
compressing.zip
.compressDir(this.option.filePath + '/chart', zipPath)
.then(() => {
console.log(`Tip: 文件压缩成功,已压缩至【${this.option.filePath}】`);
})
.catch(err => {
console.log(err, "Tip: 压缩报错");
});
} else {
}
})
}
}
module.exports = Zip
webpack.prod.conf.js
//add
const zipPlugin = require('./zipfile')
const webpackConfig = merge(...)
//直接放在外层即可
webpackConfig.plugins.push(
new zipPlugin({
filePath:path.resolve(__dirname,"../dist"),
zipPath:path.resolve(__dirname,"../dist"),
zipName:"chart"//压缩文件的名称
})
)
module.exports = webpackConfig
好啦!!!运行npm run build
压缩成功!!nice