我的目录结构类似于:
app/
directory1/
assets/
images/
js/
directory2/
assets/
images/
dist/
assets/
images/
js/
我尝试使用Gulp实现的目的是从目录1,2中“收集”资产,然后将它们放入dist / assets /中,所以我写了这个:
gulp.task('gather-assets', function() {
gulp.src('app/*/assets/**').pipe(gulp.dest('dist/assets/'));
});
问题是在运行此函数后,它将创建一个这样的路径:
dist/assets/directory1/assets/images
按照this question的建议,我尝试使用gulp-rename,但我的情况有所不同,如果我像这样使用gulp-rename:
gulp.task('gather-assets', function() {
gulp.src('app/*/assets/**').pipe(rename({dirname: ''})).pipe(gulp.dest('dist/assets/'));
});
它肯定会在*星号的位置删除不必要的路径,但它也会删除**路径。因此,来自images /和js /的文件将被复制到assets / without子目录。在这种情况下,我可以使用哪种解决方案?
答案 0 :(得分:2)
Gulp-flatten会对你有用。
var flatten = require('gulp-flatten');
gulp.task('gather-assets', function() {
return gulp.src('app/*/assets/**')
// .pipe(rename({ dirname: '' }))
// -2 will keep the last two parents : assets/images or assets/js
.pipe(flatten({ includeParents: -2 }))
.pipe(gulp.dest('dist'));
});
如果你想使用gulp-rename:[gulp-flatten和gulp-rename只是对每个文件的目录结构进行字符串操作]
// .pipe(flatten({ includeParents: -2 }))
.pipe(rename(function (file) {
let tempArray = file.dirname.split(path.sep);
// remove the first array item : directory1 or directory2
// rejoin the remaining array items into a directory string
let temp = tempArray.slice(1).join(path.sep);
file.dirname = temp;
}))