Gulp: 编译 mustache 时避免使用中间文件

Gulp: avoid intermediate files when compiling mustache

我的存储库中有以下目录结构:

src
  some-project
    some-file.html
    some-file.yml
  other-project
    foo.html
    foo.yml
    bar.html
    bar.yml
  stylesheet.css

dist
  some-project
    some-file.html
    some-file.yml
  other-project
    foo.html
    foo.yml
    bar.html
    bar.yml

我有一个 gulp 任务,它获取由 /src 文件夹中的 html 文件添加的任何样式表中的样式,并自动将它们内联到 html(这些是电子邮件). yml 是发送数据时使用的元信息。

现在我想为我的 HTML 添加小胡子模板。模板的数据将在 yml 文件中。我遇到的问题是 gulp-mustache 插件为其模板输入采用流,并为其数据采用参数中的对象。

gulp.task('build', () => {
  gulp.src('src/**/*.html')
    .pipe(mustache(data)) // I don't have the data!
    .pipe(inlineCss({
      removeStyleTags: false
    }))
    .pipe(prefix(BASE_URL, [ { match: "img[src]", attr: "src"} ]))
    .pipe(gulp.dest('dist'))
});

我有另一个任务可以将 YML 编译为 JSON,但我试图避免创建临时文件,因为它破坏了拥有 gulp 的虚拟文件流的全部意义。此外,它并没有解决我有两个任务和两个 gulp 管道的问题,我无法将一个文件的内容传递给 mustache 函数。有什么我想念的吗?

这似乎是一个非常简单的任务,我已经搜索了几个小时没有任何进展。 gulp 没有一种方法可以每对读取文件吗?

好的,我注意到的第一件事是您没有在 Gulp 任务中返回任何内容,这使得 Gulp 无法知道您的任务何时完成。

由于任务本身是异步的,并且 Gulp 支持任务 returning a Promise that will signal completion when it resolves, you could do something like that, using node-yaml 包,其中 returns 也是一个 Promise:

const yaml = require('node-yaml')

gulp.task('build', () => {
  return yaml.read('my-data.yml').then(data =>
    new Promise(resolve => {
      gulp.src('src/**/*.html')
        .pipe(mustache(data))
        // ...
        .pipe(gulp.dest('dist'))
        .on('end', resolve)
    });
  );
});

或者简单地使用 callbacks:

gulp.task('build', callback => {
  return yaml.read('my-data.yml', data => {
    gulp.src('src/**/*.html')
      .pipe(mustache(data))
      // ...
      .pipe(gulp.dest('dist'))
      .on('end', callback)
  });
});