Gulp 插件的条件设置取决于源文件

Conditional settings for Gulp plugins dependent on source file

插件 gulp-pug 允许通过 data 属性 将全局变量传递给 pug 文件。 如果我们不需要每个 .pug 文件中的完整数据集怎么办?要实现条件数据注入,我们需要访问 pipe(this.gulpPlugins.pug({}) 内的当前 vinyl 文件实例,或者至少知道源文件的绝对路径。可能吗?

const dataSetForTopPage = {
    foo: "alpha",
    bar: "bravo"
};

const dataSetForAboutPage = {
    baz: "charlie",
    hoge: "delta"
};


gulp.src(sourceFileGlobsOrAbsolutePath)
    .pipe(gulpPlugins.pug({
      data: /* 
       if path is 'top.pug' -> 'dataSetForTopPage',  
       else if path is 'about.pug' -> 'dataSetForAboutPage'
       else -> empty object*/
    }))
    .pipe(Gulp.dest("output"));

我正在使用 gulp-intercept 插件。但是如何与gulpPlugins.pug同步呢?

gulp.src(sourceFileGlobsOrAbsolutePath)
    .pipe(this.gulpPlugins.intercept(vinylFile => {
      // I can compute conditional data set here
      // but how to execute gulpPlugins.pug() here?
    }))
    // ...

这只是一个例子,但当需要为其他 gulp 插件设置条件插件选项时,我们也会处理同样的问题。例如:

.pipe(gulpPlugins.htmlPrettify({ 
  indent_char: " ", 
  indent_size: // if source file in 'admin/**' -> 2, else if in 'auth/**' -> 3 else 4
}))

您需要手动修改流 - through2 可能是用于此目的最常用的软件包。进入 through2 回调后,您可以将流传递给 gulp 插件(只要它们的转换函数公开)并有条件地传递给它们选项。例如,这里有一个任务:

pugtest = () => {
    const dataSet = {
        'top.pug': {
            foo: "alpha",
            bar: "bravo"
        },
        'about.pug': {
            foo: "charlie",
            bar: "delta"
        }
    };

    return gulp.src('src/**/*.pug')
        .pipe(through2.obj((file, enc, next) => 
            gulpPlugins.pug({
                // Grab the filename, and set pug data to the value found in dataSet by that name
                data: dataSet[file.basename] || {}
            })._transform(file, enc, next)
        ))
        .pipe(through2.obj((file, enc, next) => {
            const options = {
                indent_char: ' ',
                indent_size: 4
            };

            if(file.relative.match(/admin\//)) {
                options.indent_size = 2;
            } else if(file.relative.match(/auth\//)) {
                options.indent_size = 3;
            }

            file.contents = new Buffer.from(html.prettyPrint(String(file.contents), options), enc);
            next(null, file);
        }))
        .pipe(gulp.dest('output'));
}

对于 pug 步骤,我们调用 through2.obj 并创建 pug 插件,将从我们的对象字面量中获取的数据传递给它,在本例中按文件名索引。所以现在传递给编译器的数据来自那个对象字面量。

对于您提到的 html 步骤,gulp-html-prettify doesn't expose its transform function, so we can't reach into it and pass the transform back to the stream. But in this case that's OK, if you look at the source it's just a wrapper to prettyPrint in the html 包。这就是它所做的一切。所以我们可以使用 through2 来完成我们的步骤来做同样的事情,但是根据乙烯基文件的相对路径改变我们的选项。

就是这样!有关工作示例,请参阅此 repo:https://github.com/joshdavenport/stack-overflow-61314141-gulp-pug-conditional