Webpack5 自定义plugin的编写 解决html空div、空行以及注释问题

121 阅读1分钟

项目地址:gitee.com/luobf22/vue…

本文旨在编写解决html空div、空行以及注释问题的自定义plugin

在index.html 加入2个空div和1个注释

image.png

通过自定义plugin成功去掉空div和注释以及空行问题

image.png

const cheerio = require('cheerio');
// 18.17 可能需要node 18.17 版本
class MyPlugin {
    apply(compiler) {
        compiler.hooks.emit.tap('MyPlugin', (compilation) => {
            // 遍历所有输出的文件资源
            Object.keys(compilation.assets).forEach((file) => {
                if (file.endsWith('.html')) {
                    const asset = compilation.assets[file];
                    //  content 是当前html 页面里的所有内容
                    const content = asset.source();
                    // // 使用cheerio加载HTML内容,类似在浏览器中操作DOM
                    const $ = cheerio.load(content);
                    // 找到所有空的div元素并删除它们
                    $('div:empty').each((index, element) => {
                        if ($(element).attr('id') !== 'app') {
                            $(element).remove();
                        }
                    });
                    // 将注释去掉
                    $('*').contents().each((i, element) => {
                        if (element.type === 'comment') {
                            $(element).remove();
                        }
                    });
                    const newContent = $.html().replace(/\n\s*\n/g, '\n');
                    compilation.assets[file] = {
                        // source: () => $.html(),
                        // size: () => Buffer.from($.html()).length
                        source: () => newContent,
                        size: () => Buffer.from(newContent).length
                    };
                }
            });
        });
    }
}

![image.png](https://p6-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/fbea70c5e3d842c2af48382f8fda004d~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5bGx5rW35LiN5YaN6L-c:q75.awebp?rk3s=f64ab15b&x-expires=1771838564&x-signature=QJMBWJ7ER5A9H5tx3SUt5FlUq%2Fo%3D)
module.exports = MyPlugin;

自定义plugin相较于官方plugin或者loader的好处:

  • 可以根据项目的特定需求来定制构建过程
  • 能够精确地控制构建流程的各个阶段
  • 自定义插件可以实现对资源更精细的优化
  • 自定义的plugin比官方的loader更轻量,有时候解决一个小问题,不需要使用到所有的loader