我正在使用 purgeCSS 删除未使用的 CSS。我的挑战是我需要动态地做到这一点。根据正在处理的当前 .css 文件,我需要获取其路径和文件名,以便动态插入内容 HTML 路径以运行 Purge。
这是我的代码的样子:
const gulp = require("gulp"),
appRoot = require("app-root-path"),
sass = require("gulp-sass"),
purgecss = require("gulp-purgecss"),
tap = require("gulp-tap"),
path = require("path"),
utilities = require(appRoot + "/Tools/Utilities-Functions/utilities-functions.js");
gulp.task("sass", () => {
let htmlContentPath = "";
return (
gulp
.src("./Pages/**/*.scss")
// Compile .scss into .css
.pipe(sass())
// Get path for HTML file (dynamic)
.pipe(
tap(function (file, t) {
let fileName = path.basename(file.path);
// This is a simple function that returns the file name without extension (homepage.css >> homepage)
fileName = utilities.getFileNameWithoutExtension(fileName);
htmlContentPath = "/fullPath/Pages/" + fileName + "/compiled/html/" + fileName + ".html";
})
)
// Remove unused CSS
.pipe(
purgecss({
content: [htmlContentPath]
})
)
// Set the destination folder (main css)
.pipe(gulp.dest("./dist/css"))
);
})
由于某种原因,Purge 的“htmlContentPath”为空。即使我希望“点击”插件总是为它设置一个值。结果,这会在 purgecss 上引发错误:
如上所述,此错误是由于“htmlContentPath”为空。
我尝试的另一个尝试是在 Tap 插件中执行 Purge,如下所示:
const gulp = require("gulp"),
appRoot = require("app-root-path"),
sass = require("gulp-sass"),
purgecss = require("gulp-purgecss"),
tap = require("gulp-tap"),
path = require("path"),
utilities = require(appRoot + "/Tools/Utilities-Functions/utilities-functions.js");
gulp.task("sass", () => {
return (
gulp
.src("./Pages/**/*.scss")
// Compile .scss into .css
.pipe(sass())
// Get path for HTML file (dynamic)
.pipe(
tap(function (file, t) {
let fileName = path.basename(file.path);
// This is a simple function that returns the file name without extension (homepage.css >> homepage)
fileName = utilities.getFileNameWithoutExtension(fileName);
let htmlContentPath = "/fullPath/Pages/" + fileName + "/compiled/html/" + fileName + ".html";
// Remove unused CSS
purgecss({
content: [htmlContentPath]
})
})
)
// Set the destination folder (main css)
.pipe(gulp.dest("./dist/css"))
);
})
这次它没有给出错误,但是 Purge 完全被忽略了......
关于如何解决这个问题的任何解决方案?