求推荐可清理HTML空class、class值多余空格的Gulp格式化插件
实现方案
没有完全精准匹配这三个规则的开箱即用Gulp插件,最稳妥、不会破坏原有HTML格式的实现方式是用gulp-posthtml配合十几行自定义逻辑实现,全程不会做多余的压缩、格式改动,完全符合你的需求。
具体操作
- 先安装需要的依赖,在项目目录执行命令:
npm install gulp gulp-posthtml -D - 在你的
gulpfile.js中写入如下任务逻辑:
const gulp = require('gulp'); const posthtml = require('gulp-posthtml'); function htmlClassOptimize() { // 自定义class处理插件 const classFixer = (tree) => { tree.match({ attrs: { class: /.*/ } }, (node) => { const classValue = node.attrs.class.trim(); if (!classValue) { // 值为空直接移除class属性,其他属性完整保留 delete node.attrs.class; } else { // 清除首尾空格,把内部连续的多空格替换为单个空格 node.attrs.class = classValue.replace(/\s{2,}/g, ' '); } return node; }); return tree; }; return gulp.src('src/**/*.html') // 替换为你的HTML源文件路径 .pipe(posthtml([classFixer], { // 关闭所有默认格式改动,保留原HTML排版 render: { quoteAllAttributes: true, closingSingleTag: 'default' } })) .pipe(gulp.dest('dist/')); // 替换为你的输出路径 } exports.default = htmlClassOptimize;
执行该任务后,输出结果完全匹配你的预期:
<button disabled></button> // remove empty class and keep other attr like disabled <div class="a b"></div> // remove whitespace around quote <div class="a b"></div> // remove double space inside class
替代方案
如果你不想写自定义逻辑,也可以尝试用gulp-htmlmin实现,需要把所有压缩、格式修改类的配置项全部关闭,只开启和class处理相关的三个配置:
removeEmptyAttributes: true自动移除值为空的属性(包含空class)trimAttributeWhitespace: true清除属性值首尾的多余空格collapseAttributeWhitespace: true合并属性值内部的连续空格
注意使用这个方案一定要仔细核对所有配置项,一旦漏关某个压缩规则,就会改动你原本的HTML格式,可控性不如上面自定义posthtml插件的方案。
内容的提问来源于stack exchange,提问作者aboutjquery
相关产品推荐
相关产品推荐

