My directories structure is similar to this:
app/
directory1/
assets/
images/
js/
directory2/
assets/
images/
dist/
assets/
images/
js/
What I try to achieve using Gulp is to "gather" assets from directories 1, 2, ... and place them into the dist/assets/ so I wrote this:
gulp.task('gather-assets', function() {
gulp.src('app/*/assets/**').pipe(gulp.dest('dist/assets/'));
});
The problem is that after running this function it will create a path like this:
dist/assets/directory1/assets/images
Following the recommendations from this question I tried to use gulp-rename, but my case is different, and if I use gulp-rename like this:
gulp.task('gather-assets', function() {
gulp.src('app/*/assets/**').pipe(rename({dirname: ''})).pipe(gulp.dest('dist/assets/'));
});
it will surely remove unnecessary path at the place of * asterisk, but it will remove the ** path as well. So files from both images/ and js/ will be copied to assets/ without subdirectories. What solution is available for me for this scenario?
Gulp-flatten will work for you.
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'));
});
And if you wanted to use gulp-rename: [both gulp-flatten and gulp-rename are just doing string manipulations of each file's directory structure]
// .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;
}))