CleanWebpackPlugin 插件用于删除/清理构建文件夹。
准备工作
npm i webpack webpack-cli
创建如下项目目录
├── plugins # 编译打包后的输出目录
├── src
│ └── index.js
├── package.json
├── package-lock.json
└── webpack.config.js
代码实现
webpack.config.js
const CleanWebpackPlugin = require('./plugin/CleanWebpackPlugin');
module.exports = {
mode: 'production',
output: {
// clean: true,
},
plugins: [
new CleanWebpackPlugin(),
],
};
plugin/CleanWebpackPlugin.js
class CleanWebpackPlugin {
apply(compiler) {
// 获取操作文件的对象
const fs = compiler.outputFileSystem;
// 绑定到 “emit” 钩子,在新的打包产物输出前进行clean
compiler.hooks.emit.tapAsync('CleanWebpackPlugin', (compilation, callback) => {
// 获取输出文件目录
const outputPath = compiler.options.output.path;
// 删除目录所有文件
this.removeFiles(fs, outputPath);
callback();
});
}
removeFiles(fs, filePath) {
console.log('filePath', filePath);
// 读取当前目录下所有文件
const exists = fs.existsSync(filePath);
console.log('exists', exists);
const files = fs.existsSync(filePath) ? fs.readdirSync(filePath) : [];
// 递归删除
files.forEach((file) => {
// 获取文件完整路径
const path = `${filePath}/${file}`;
// 判断是否是文件夹
if (fs.statSync(path).isDirectory()) {
// 是文件夹则需要递归
this.removeFiles(fs, path);
} else {
// 是文件则要直接删除,且是同步删除
fs.unlinkSync(path);
}
});
if (exists) {
// 最后删除当前目录
fs.rmdirSync(filePath);
}
}
}
module.exports = CleanWebpackPlugin;
验证测试
执行 npx webpack,可以看到打包结果如下,符合期待。

源码:https://gitee.com/yanhuakang/webpack-demos/tree/master/proficient/step_7-CleanWebpackPlugin

文章介绍了如何使用CleanWebpackPlugin插件在webpack构建过程中删除输出目录的文件。首先,通过npm安装webpack和webpack-cli,然后设置项目目录结构。接着,引入CleanWebpackPlugin插件到webpack配置,并在emit钩子中清除输出目录。最后,展示了CleanWebpackPlugin类的实现,包括删除文件和目录的方法。
3970

被折叠的 条评论
为什么被折叠?



