Search code examples
gulp

How to compile the file and keeping same folder structure using gulp?


I want to compile all the pug files.

Here's my src folder structure

src
  pug
    a
      a.pug
    b
      b.pug

I want gulp to compile all the pug files but keeping the folder structure same in the dest folder.

This should be the dest folder structure

dest
  a
    a.html
  b
    b.html

I have tried to use this code, but it is not working, the location where it sends all the HTML files to: dest/src/pug.

function getFolders(dir) {
  return fs.readdirSync(dir).filter(function(file) {
    return fs.statSync(path.join(dir, file)).isDirectory();
  });
}

var pugPath = "src/pug";

gulp.task("html", function() {
  var folders = getFolders(pugPath);
  var tasks = folders.map(function(folder) {
    return gulp
      .src([
        path.join(pugPath, folder, "src/pug/**/*.pug"),
        "!" + pugPath + "/includes/**/*.pug"
      ])
      .pipe(pug())
      .pipe(gulp.dest(paths.dest.html));
  });

  var root = gulp
    .src(path.join(pugPath, "src/pug/**/*.pug"))
    .pipe(pug())
    .pipe(gulp.dest(paths.dest.html));

  return merge(tasks, root);
});

Solution

  • It seems like most of this code could be tossed if you used a glob like src/pug/**/*.pug to grab all files in a folder recursively - then pipe to dest('test'). The way you're combining folders is most likely where the bug is.

    gulp.task("html", function() {
      return gulp.src([ 'src/pug/**/*.pug', '!src/pug/includes/**/*.pug' ])
        .pipe(pug())
        .pipe(gulp.dest('test'));
    });