在 Gulp 任务中根据文件名有条件地创建目录

Conditionally creating directories from filenames in Gulp task

我的 source 目录中有以下结构:

|-source
  |-home.pug
  |-page1.pug
  |-page2.pug

我希望在我的 dest 目录中找到它:

|-dest
  |-index.html (former home.pug)
  |-page1/index.html (former page1.pug)
  |-page2/index.html (former page2.pug)

我的 Gulpfile.js 看起来像这样:

var
  gulp = require('gulp'),
  gulpif = require('gulp-if'),
  gzip = require('gulp-gzip'),
  htmlmin = require('gulp-htmlmin'),
  path = require('path'),
  pug = require('gulp-pug'),
  rename = require('gulp-rename');

gulp.task('views', function() {

  gulp.src('source/!(home)*.pug')
    .pipe(pug())
    .pipe(rename(function(file) {
      file.dirname = path.join(file.dirname, file.basename);
      file.basename = 'index';
      file.extname = '.html';
    }))
    .pipe(htmlmin())
    .pipe(gulp.dest('dest/'))

  gulp.src('source/home.pug')
    .pipe(pug())
    .pipe(rename(function(file) {
      file.basename = 'index';
      file.extname = '.html';
    }))
    .pipe(htmlmin())
    .pipe(gulp.dest('dest/'))
});

如您所见,有两个块在顶部和底部使用相同的代码。我想找到一个更优的解决方案。

我添加了 gulp-if 并尝试实现 if-else 逻辑:

gulp.task('views', function() {
  gulp.src('source/*.pug')
    .pipe(pug())
    .pipe(gulp-if(
     'home.pug',
     rename(function(file) {
      file.basename = 'index';
      file.extname = '.html';
    }),
     rename(function(file) {
      file.dirname = path.join(file.dirname, file.basename);
      file.basename = 'index';
      file.extname = '.html';
    })))
    .pipe(htmlmin())
    .pipe(gulp.dest('dest/'))
});

但这没有用。 Gulp 创建了一个多余的 dest/home/index.html 而不是 dest/index.html.

您的 Gulpfile 只是 JavaScript。这意味着您可以像在任何 JavaScript 程序中一样使用常规 if (test) { } 语句。不需要 gulp-if.

这甚至比使用 gulp-if 更短,并且只需要一个 rename() 操作:

gulp.task('views', function() {
  return gulp.src('source/*.pug')
    .pipe(pug())
    .pipe(rename(function(file) {
      if (file.basename !== 'home') {
        file.dirname = path.join(file.dirname, file.basename);
      }
      file.basename = 'index';
    }))
    .pipe(htmlmin())
    .pipe(gulp.dest('dest/'))
});

我还遗漏了 file.extname = '.html' 行。 pug() 插件已经将扩展名从 .pug 更改为 .html,因此您无需自己执行此操作。