Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Development Tools

Margaret Johnson
Margaret Johnson
4,275 Points

Gulp - how to loop through directories and perform same task on it's contents?

I want to compress SVGs that are used per page and then inject the compressed SVG stream into a file using a gulp task. I have directories such as ..svg/index , ...svg/about, etc. My current gulp task implementation hard codes the input and output directories and files. What is the best way to feed in a directory then do the task? Here is my current gulpfile.js:

'use strict';
const gulp = require('gulp');
const svgstore = require('gulp-svgstore');
const inject = require('gulp-inject');
const debug = require('gulp-debug');
const svgmin = require('gulp-svgmin');

// Useful functions.
function fileContents(filePath, file) {
  return file.contents.toString();
}
// Read in the SVGs used by index.html and inject the stream
// into index.html.
gulp.task('make_sprite_index',function(){
  // Compile the SVGs into a stream.
  var svgs = gulp
    .src('client/design/svg/index/*.svg')
    .pipe(debug())
    .pipe(svgmin())
    .pipe(svgstore({
        inlineSvg: true
      }))

  return gulp
    // Flask based server stores html in the templates folder.
    .src('client/design/html/index.html')
    .pipe(inject(svgs, {
      transform: fileContents
    }))
    .pipe(gulp.dest('templates'));

});
gulp.task('make_sprite_layout',function(){
  // Compile/minimize the SVGs into a stream.
  var svgs = gulp
    .src('client/design/svg/layout/*.svg')
    .pipe(debug())
    .pipe(svgmin())
    .pipe(svgstore({
        inlineSvg: true
      }))
  // return the file in the distribution directory after SVG has been injected.
  return gulp
    // Flask based server stores html in the templates folder.
    .src('client/design/html/layout.html')
    .pipe(inject(svgs, {
      transform: fileContents
    }))
    .pipe(gulp.dest('templates'));

});

thank you.