Javascript 根据Gulp任务中的文件名有条件地创建目录
我的Javascript 根据Gulp任务中的文件名有条件地创建目录,javascript,optimization,gulp,conditional,pug,Javascript,Optimization,Gulp,Conditional,Pug,我的源代码目录中有以下结构: |-source |-home.pug |-page1.pug |-page2.pug |-dest |-index.html (former home.pug) |-page1/index.html (former page1.pug) |-page2/index.html (former page2.pug) 我希望在我的dest目录中得到这个: |-source |-home.pug |-page1.pug |-page
源代码
目录中有以下结构:
|-source
|-home.pug
|-page1.pug
|-page2.pug
|-dest
|-index.html (former home.pug)
|-page1/index.html (former page1.pug)
|-page2/index.html (former page2.pug)
我希望在我的dest
目录中得到这个:
|-source
|-home.pug
|-page1.pug
|-page2.pug
|-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/'))
});
如您所见,在顶部和底部有两个块使用相同的代码。我想找到一个更理想的解决方案
我添加了gulpif
,并尝试实现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){}
语句。如果,则无需吞咽
这甚至比使用galpif
更短,并使您简化为一个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
,因此您不需要自己执行此操作。您的Gulpfile只是JavaScript。这意味着您可以像在任何JavaScript程序中一样使用常规的if(test){}
语句。如果
,则无需吞咽
这甚至比使用galpif
更短,并使您简化为一个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
,因此您无需自己执行此操作