首页 > 解决方案 > 如何使用 gulp 编译文件并保持相同的文件夹结构?

问题描述

我想编译所有的 pug 文件。

这是我的 src 文件夹结构

src
  pug
    a
      a.pug
    b
      b.pug

我希望 gulp 编译所有 pug 文件,但在 dest 文件夹中保持文件夹结构相同。

这应该是 dest 文件夹结构

dest
  a
    a.html
  b
    b.html

我曾尝试使用此代码,但它不起作用,它将所有 HTML 文件发送到的位置: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);
});

标签: gulp

解决方案


如果您使用像 src/pug/**/*.pug 这样的 glob 递归地抓取文件夹中的所有文件,那么似乎大部分代码都可能被丢弃 - 然后通过管道传递到 dest('test')。您组合文件夹的方式很可能是错误所在。

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

推荐阅读