首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Gulp任务中的文件名中有条件地创建目录

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

Stack Overflow用户
提问于 2016-12-22 06:47:22
回答 1查看 335关注 0票数 1

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

代码语言:javascript
复制
|-source
  |-home.pug
  |-page1.pug
  |-page2.pug

我希望在我的dest目录中得到这样的信息:

代码语言:javascript
复制
|-dest
  |-index.html (former home.pug)
  |-page1/index.html (former page1.pug)
  |-page2/index.html (former page2.pug)

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

代码语言:javascript
复制
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逻辑:

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-22 07:30:16

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

这甚至比使用gulp-if更短,可以让您进入一个单独的rename()操作:

代码语言:javascript
复制
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,所以不需要自己做。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41277255

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档