如何将球形gulp.src文件移动到嵌套的gulp.dest文件夹中

问题描述

问题第1部分:输出到嵌套的动态文件

我使用 Gulp.js 进行图形电子邮件开发。。我的雇主正在切换到另一个营销平台,该平台要求我们的电子邮件模板位于不同的文件夹结构中。 当gulp.src使用globbing时,我无法输出到嵌套文件夹。感谢您的帮助!

这是gulp.src文件夹的简化示例:

build/template1/template1.html
build/template2/template2.html
build/template3/template4.html
build/template4/template4.html

这是gulp.src文件夹的简化示例:

build/template1/theme/html/template1.html
build/template2/theme/html/template2.html
build/template3/theme/html/template4.html
build/template4/theme/html/template4.html

我想对动态模板文件夹做类似通配符的操作...

gulp.task('moveFile',function(){
  return gulp.src('./build/*/*.html')
  .pipe(gulp.dest('./build/*/theme/html'));
});

...但是,只有在gulp.src中才能使用通配符。 使用全局gulp.src时如何输出到动态文件夹?我能得到的最接近的结果是将/ theme文件夹放置在与模板文件夹相同的级别上,而不是根据需要放在每个文件夹内。 / p>

谢谢您的帮助!

问题第2部分:将*重命名文件*输出到嵌套的动态文件

Mark回答了我的问题(谢谢@Mark!),但是我过度简化了用例,因此我添加了第2部分。

除了嵌套文件外,我还需要重命名它。 (我本来是要工作的,但是无法使这两个部分协同工作。)参考gulp-rename文档,我做了3次不同的尝试。它是如此之近,但我希望获得更多帮助。 :-)

// ATTEMPT 1: Using gulp-rename mutating function method
gulp.task('createTwig',function(){
  return gulp.src('./build/*/*.html')
    .pipe(rename(
      function (path) {
        path.basename = "email";
        path.extname = ".html.twig";
      },function (file) {
        console.log(file.dirname);
        file.dirname = nodePath.join(file.dirname,'theme/html');
      }
    ))
    .pipe(gulp.dest('./build/'));
});

// ATTEMPT 2: Using gulp-rename fixed object method
gulp.task('createTwig',function(){
  return gulp.src('./build/*/*.html',{ base: process.cwd() })
    .pipe(rename(
      {
        basename: "email",extname: ".html.twig"
      },'theme/html');
      }
    ))
    .pipe(gulp.dest('./build/'));
});

// ATTEMPT 3: Using gulp-rename mutating function method
gulp.task('createTwig',function(){
  return gulp.src('./build/*/*.html')
    .pipe(rename(
      function (path,file) {
        path.basename = "email";
        path.extname = ".html.twig";
        console.log(file.dirname);
        file.dirname = nodePath.join(file.dirname,'theme/html');
      }
    ))
    .pipe(gulp.dest('./build/'));
});

解决方法

这有效:

const rename = require("gulp-rename");
const path = require("path");


gulp.task('moveFile',function(){
  return gulp.src(['build/**/*.html'])

    .pipe(rename(function (file) {
      console.log(file.dirname);
      file.dirname = path.join(file.dirname,'theme/html');
    }))

    .pipe(gulp.dest('build'))   // build/template1/theme/html
});

我尝试了几种方法,包括尝试base选项和gulp-flatten并在gulp.dest中使用函数,但这是最简单的。


问题第2部分:

gulp.task('createTwig',function(){
  return gulp.src(['build/**/*.html'])

  .pipe(rename(function (file) {

    file.basename = "email";
    file.extname = ".html.twig";
  
    file.dirname = path.join(file.dirname,'theme/html');
  }))

  .pipe(gulp.dest('build'))   // build/template1/theme/html
});

path.basename/extname仅仅是“获取器”,您无法设置这些值。