Search code examples
node.jsgulppugfilestream

How to carry a variable from one pipe to another in Gulp


gulp.task('jade:prod:DE_EN', function () {
return gulp.src('./views/*.jade')
    .pipe(tap(function(file) {
        console.log(path.basename(file.path))
    }))
    .pipe(jade({
        locals: {
            env: 'production',
            texts: texts.EN,
            config: texts.EN['config']
        }
    }))
    .pipe(gulp.dest('./public/de/en'));
});

console.log(path.basename(file.path)) returns whichever .jade file is passing through the stream.

I want to know how I can get that variable and pass it into the jade pipe as one of the locals. So that I can use it in Jade at compile time.

Any additional links/references/documentation that explain how piping / streams work would be appreciated.


Solution

  • The only way to get data from one Transform (the thing you pass to pipe()) to the next is to attach it to the vinyl-fs file object that is moving through the stream. The gulp-data plugin let's you do just that:

    gulp.task('jade:prod:DE_EN', function () {
      return gulp.src('./views/*.jade')
        .pipe(data(function(file) {
           return { 
             myBasename: path.basename(file.path),
             env: 'production',
             texts: texts.EN,
             config: texts.EN['config']
           };
        }))
       .pipe(jade())
       .pipe(gulp.dest('./public/de/en'));
    });
    

    Now you can access the myBasename local in your Jade template:

    doctype html
    html(lang="en")
      head
        title=Test
      body
        h1 #{myBasename}