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

时间:2016-12-22 06:47:23

标签: javascript optimization gulp conditional pug

我的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

1 个答案:

答案 0 :(得分:0)

您的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,因此您无需自行执行此操作。

相关问题