javascriptgulpgulp-replace

Use Gulp to check if a token exists in a file


If I do this:

var gulp = require('gulp');
var replace = require('gulp-replace');
var rename = require('gulp-rename');

gulp.task('TaskExample', function ReplaceExampleFileTokens() {

    return gulp.src('./src/' + 'ExampleFileTokens.config')

        .pipe(replace('#{String}#', 'Hello World'))
        .pipe(rename('ExampleFile.config'))
        .pipe(gulp.dest('./dest'));
    });

I will:

  1. replace the token in ExampleFileTokens.config then

  2. rename it to ExampleFile.config and

  3. finally deposit it in './dest'.

My questions are the following:


Solution

  • I don't think there is a way to have gulp-replace do all the work you want. It is troublesome to set a conditional within a stream.

    You can do it easily enough with a filter though (gulp-filter.

    const gulp = require('gulp');
    const replace = require('gulp-replace');
    const rename = require('gulp-rename');
    
    const filter = require('gulp-filter');
    const filterEach = require('gulp-filter-each')
    
    gulp.task("TaskExample", function () {
    
      // return true if want the file in the stream
      // const configFilter = filter(function (file) {       
      //   let contents = file.contents.toString();
      //   return contents.match('#{String}#');
      // });
    
      return gulp.src('./src/' + 'ExampleFileTokens.config')
    
        // you can use either of the following two filters
        // .pipe(configFilter)
        .pipe(filterEach(content => content.match('#{String}#')))
    
        .pipe(replace('#{String}#', 'Hello World'))
        .pipe(rename('ExampleFile.config'))
        .pipe(gulp.dest('./dest'));
    });