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

时间:2017-06-13 00:46:01

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

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

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

以下Gulp任务为每个文件运行inliner(),但似乎无法将结果注入流中。我尝试了一些不同的方法,但我似乎无法将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错误吗?这似乎是一个非常简单的用例。

2 个答案:

答案 0 :(得分:1)

当我为每个文件输入短语&#34;&#34;时,我记得有一个gulp-foreach包,它有效!我的新代码如下所示:

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

如果有人愿意分享为什么我的原始代码无效...为什么gulp-tap似乎不允许您将内容重新注入管道,那就是太棒了否则,吸取教训:

用户gulp-foreach,而不是gulp-tap,如果您想重新进入管道。

答案 1 :(得分:1)

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'));
}

感谢Elliot,这对我也很有帮助,但我还没有对你的帖子发表评论,因为还没有足够的代表!