How can I use gulp to replace a string in a file?

Gulp streams input, does all transformations, and then streams output. Saving temporary files in between is AFAIK non-idiomatic when using Gulp.

Instead, what you’re looking for, is a streaming-way of replacing content. It would be moderately easy to write something yourself, or you could use an existing plugin. For me, gulp-replace has worked quite well.

If you want to do the replacement in all files it’s easy to change your task like this:

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

gulp.task('scripts', ['clean-js'], function () {
    return gulp.src(js.src)
      .pipe(replace(/http:\/\/localhost:\d+/g, 'http://example.com'))
      .pipe(uglify())
      .pipe(concat('js.min.js'))
      .pipe(gulp.dest('content/bundles/'))
      .pipe(gzip(gzip_options))
      .pipe(gulp.dest('content/bundles/'));
});

You could also do gulp.src just on the files you expect the pattern to be in, and stream them seperately through gulp-replace, merging it with a gulp.src stream of all the other files afterwards.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)