我需要一個 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嗎?
謝謝你。
uj5u.com熱心網友回復:
您可以使用一些節點 dom 庫,并用 gulp 包裝它。例如,您可以嘗試使用 jsdom 和包裝器 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"));
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364717.html
標籤:javascript 新产品经理 吞咽
