问题
I'm trying to optimize images in a couple of different locations using Gulp. This is the directory structure:
|-- app
|-- _images
-- image1.jpg
-- image2.jpg
|-- _templates
|-- _pages
|--_services
|--_images
-- image1.jpg
-- image2.jpg
And this is the code
gulp.task('images:tmp', function() {
return gulp.src(['app/templates/pages/**/*.{png,jpg,gif,svg}', 'app/images/**/*.{png,jpg,gif,svg}'], {base: 'app/'})
// Caching images that ran through imagemin
.pipe(cache(imagemin({
interlaced: true,
})))
.pipe(gulp.dest('.tmp'))
});
The problem I'm having is that the app's "templates" and "pages" directories are copied into the root of ".tmp," along with the "services" directory:
|-- .tmp
|-- _images
-- image1.jpg
-- image2.jpg
|-- _templates
|-- _pages
|--_services
|--_images
-- image1.jpg
-- image2.jpg
I only want the "services" directory in the root, like so:
|-- .tmp
|-- _images
-- image1.jpg
-- image2.jpg
|-- _services
|--_images
-- image1.jpg
-- image2.jpg
How do I write the task to replicate the directory structure above? Thanks in advance for your help!
回答1:
(I cannot add this as a comment)
Split your source stream in two streams and return merged stream as per the recipe at https://github.com/gulpjs/gulp/blob/master/docs/recipes/using-multiple-sources-in-one-task.md :
var merge = require('merge-stream');
gulp.task('images:tmp', function() {
var stream1 = gulp.src('app/templates/pages/**/*.{png,jpg,gif,svg}')
.pipe(cache(imagemin({interlaced: true})))
.pipe(gulp.dest('.tmp'))
);
var stream1 = gulp.src('app/images/**/*.{png,jpg,gif,svg}',{base: 'app/'})
.pipe(cache(imagemin({interlaced: true})))
.pipe(gulp.dest('.tmp'))
);
return merge(stream1,stream2);
});
回答2:
Thanks, maoizm. This worked for me after editing the second "var stream1" to read "var stream2" and removing the apparently superfluous ); from the streams.
gulp.task('images:tmp', function() {
var stream1 = gulp.src('app/templates/pages/**/*.{png,jpg,gif,svg}')
.pipe(cache(imagemin({interlaced: true})))
.pipe(gulp.dest('.tmp'));
var stream2 = gulp.src('app/images/**/*.{png,jpg,gif,svg}',{base: 'app/'})
.pipe(cache(imagemin({interlaced: true})))
.pipe(gulp.dest('.tmp'));
return merge(stream1,stream2);
});
来源:https://stackoverflow.com/questions/38015384/replicating-directory-structure-in-gulp-dest