我的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。
发布于 2016-12-22 07:30:16
您的Gulpfile只是JavaScript。这意味着您可以像在任何if (test) { }程序中一样使用常规的JavaScript语句。不需要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,所以不需要自己做。
https://stackoverflow.com/questions/41277255
复制相似问题