node.js - 如何使用 gulp-tap 将文件名传递给 Gulp 管道中的下一个操作?

标签 node.js gulp node-streams gulp-tap

我有一个 Gulp 任务,它使用 gulp-inline-css 获取 HTML 文件和从 CSS 文件获取的内联样式。我的任务的原始版本对每个 HTML 文件使用相同的 CSS 文件。现在我想让任务根据它正在处理的 HTML 文件的文件名选择一个 CSS 文件。

我正在使用gulp-tap来获取文件名。 inliner() 函数获取 CSS 文件的路径并运行所有内联内容。

以下 Gulp 任务为每个文件运行 inliner(),但似乎无法将结果注入(inject)回流中。我尝试了几种不同的方法,但我似乎无法将 inliner() 的结果返回到原始流中。

gulp.task('inline', inline);

function inline() {
  return gulp.src('dist/**/*.html')
    .pipe(tap( (file, t) => {
      let fileName = path.basename(file.path);
      let cssPath = getStylesheetPathFromHtmlPath(fileName);
      return inliner(cssPath);
    }))
    .pipe(gulp.dest('dist'));
}

function inliner(cssPath) {
  var css = fs.readFileSync(cssPath).toString();
  var mqCss = siphon(css);
  var pipe = lazypipe()
    .pipe(inlineCss, {
      applyStyleTags: false,
      removeStyleTags: true,
      preserveMediaQueries: true,
      removeLinkTags: false
    })
    .pipe(replace, '<!-- <style> -->', `<style>${mqCss}</style>`)
    .pipe(replace, `<link rel="stylesheet" type="text/css" href="css/${getStylesheetNamespace(cssPath)}.css">`, '')
    .pipe($.htmlmin, {
      collapseWhitespace: true,
      minifyCSS: true
    });
  console.log(cssPath)
  return pipe();
}

我是否错误地使用了 gulp-tap?这看起来是一个非常简单的用例。

最佳答案

gulp-foreach 已被 gulp-tap 和 gulp-flatmap 弃用。 gulp-flatmap 是您在这里需要的,因此与 elliotregan 的答案完全相同,但如下所示:

function inline() {
  return gulp.src('dist/**/*.html')
    .pipe(flatmap((stream, file) => {
      let fileName = path.basename(file.path);
      let cssPath = getStylesheetPathFromHtmlPath(fileName);
      return stream 
        .pipe(inliner(cssPath));
    }))
    .pipe(gulp.dest('dist'));
}

谢谢埃利奥特,这也对我有帮助,但我无法评论你的帖子,因为还没有足够的代表!

关于node.js - 如何使用 gulp-tap 将文件名传递给 Gulp 管道中的下一个操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44510725/

相关文章:

node.js - gulp nodemon + Node = 错误 : listen EADDRINUSE

javascript - Node Stream - 将多个 Transform 流输出到单个 PassThrough 流

node.js - 在 node.js 中正确使用 _writev

javascript - 通过NodeJS获取OPSkins价目表的平均价格

javascript - 版本控制包文件

javascript - 可以将 &lt;script&gt;(或 &lt;style&gt;)标签提取到新的单独文件中的 Gulp 模块

node.js - 如何在可读的http流上运行Sharp转换并写入文件

javascript - 为什么数组上的js映射会修改原始数组?

node.js - Node : Send Ctrl+C to a child process on Windows

node.js - 对一个查询中具有多个条件的文档进行计数