You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求推荐可清理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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 06:51:21