2016-12-22 77 views
1

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

回答

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,因此您無需親自操作。

+0

謝謝,斯文。它很棒! –