我需要编写一个自定义 Gulp 任务,它将从我的 HTML 中删除属性

I need to write a custom Gulp task that will remove attributes from my HTML

我需要一个 Gulp 任务,它将遍历所有分配的 HTML 文档并删除某些属性(例如 style="")。我以为我可以像通过浏览器那样做,但看起来不行。这是我正在尝试做的事情:

// function to take multiple attributes from an element
const discardAttributes = (element, ...attributes) =>
  attributes.forEach((attribute) => element.removeAttribute(attribute));

// run the function on multiple elements
document.querySelectorAll("table, thead, tbody, tr, th, td").forEach((elem) => {
  discardAttributes(elem, "cellspacing", "cellpadding", "width", "style");
});

然后我想采用上面的公式并创建一个 gulp.task,如下所示:

const gulp = require("gulp");

gulp.task("clean",  async () => {
 gulp.src("src/*.html")
  .pipe(discardAttributes())
    .pipe(gulp.dest("dist"));
});

如果有我可以使用的插件,请分享,而且,我想学习如何像这样手动完成。

我需要使用 through2 吗?

谢谢。

你可以使用一些节点 dom 库,并用 gulp 包装它。例如你可以尝试 jsdom 和 wrapper gulp-dom:

const gulp = require('gulp');
const dom = require("gulp-dom");

gulp.task("default", async () => {
 gulp.src("src/*.html")
  .pipe(dom(function() {

      // function to take multiple attributes from an element
      const discardAttributes = (element, ...attributes) =>
        attributes.forEach((attribute) => element.removeAttribute(attribute));

      // run the function on multiple elements
      return this.querySelectorAll("table, thead, tbody, tr, th, td").forEach((elem) => {
       discardAttributes(elem, "cellspacing", "cellpadding", "width", "style");
    });

  }))
  .pipe(gulp.dest("dist"));
});